I came across the following C++ code in the InterviewBit for the decimal to binary conversion as displayed in the below image.
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 am unable to understand what is happening in the second statement of the while loop.
ans.push_back((char)('0' + rem));
Here is my interpretation of this code.
Suppose I take the value of n as 5.
Now for the first iteration of while loop, 5 > 0.
rem = 5%2 = 1;
In the ans string, '0' + 1(rem) i.e. "01" will be stored.
n = 5/2 = 2
Now, for second iteration, 2 > 0.
rem = 2 % 2 = 0
ans = "01" (already stored) + '0' + '0'(rem) => "0100"
n = 2/2 = 1
In final iteration, 1 > 0.
rem = 1 % 2 = 1
ans = "0100" + '0' + 1(rem) => "010001"
n = 1 / 2 = 0
- Now on reversing the answer, it will become => 100010 but it is not the correct answer.
So, can anyone please explain where I am wrong?