How does the following binary conversion decimal code work?

I came across the following C ++ code in a Bit interview for decimal binary conversion, as shown in the image below.

class Solution{

public:
  string findDigitsInBinary(int n){
    string ans;
    if(n == 0) return "0";

    while(n > 0){
      int rem = n % 2;
      ans.push_back((char)('0' + rem));
      n /= 2;
    }

    reverse(ans.begin(), ans.end());
    return ans;
  }
};

I cannot understand what is happening in the second expression of the while loop.

ans.push_back((char)('0' + rem));

Here is my interpretation of this code.

Suppose I accept n as 5.

  • Now for the first iteration of the while loop, 5> 0.

  • rem = 5% 2 = 1;

  • Ans will store "0" + 1 (rem), that is, "01".

  • n = 5/2 = 2

  • Now, for the second iteration, 2> 0.

  • rem = 2% 2 = 0

  • ans = "01" (already saved) + '0' + '0' (rem) => "0100"

  • n = 2/2 = 1

  • In the final iteration, 1> 0.

  • rem = 1% 2 = 1

  • ans = "0100" + '0' + 1 (rem) => "010001"

  • n = 1/2 = 0

  • = > 100010, .

, - , ?

+3
1

'0' + rem , : '0' - char, rem - int. int, ASCII '0' '1'.

: " int ASCII"

+4

Source: https://habr.com/ru/post/1670393/


All Articles