When I give an input as large as 12341, the program shows some weird output, why is it that?
The problem in your code lies in the way you're constructing the binary representation. You're treating the binary number as a decimal number, which means you're using the decimal system's rules to construct the binary number.
Let's break down the issue with the original code:
Treating binary as decimal
In the original code, the line ans += rem * pow(10, i); is trying to construct the binary representation as a decimal number. Here's what's happening:
remis the remainder of the division ofnumby 2, which is either 0 or 1 (the binary digit).pow(10, i)raises 10 to the power ofi, whereiis the current iteration number.ans += rem * pow(10, i)adds the product ofremandpow(10, i)toans, which is the accumulating binary representation.
The problem is that this approach is using decimal arithmetic to construct the binary representation. In decimal, each digit can have 10 values (0-9), and the place value of each digit increases by a factor of 10 as you move to the left (e.g., 10^0, 10^1, 10^2, ...). This is why pow(10, i) is used to calculate the place value of each digit.
However, in binary, each digit can only have 2 values (0 or 1), and the place value of each digit increases by a factor of 2 as you move to the left (e.g., 2^0, 2^1, 2^2, ...). By using pow(10, i), the original code is applying decimal rules to a binary system, which leads to incorrect results.
The fix: Constructing binary as a string
The revised code addresses this issue by constructing the binary representation as a string, rather than a decimal number. Here's how it works:
binaryis an empty string that will accumulate the binary digits.int rem = num & 1;calculates the remainder ofnumdivided by 2, which is the current binary digit (0 or 1).binary = (rem == 0) ? "0" + binary : "1" + binary;prepends the current binary digit to thebinarystring. Ifremis 0, it prepends "0"; otherwise, it prepends "1".- The loop continues until
numbecomes 0, at which point the complete binary representation is constructed.
By constructing the binary representation as a string, we avoid the limitations of treating binary numbers as decimal numbers. We can easily append each binary digit to the string, without worrying about decimal place values or arithmetic.
I hope this explanation helps clarify the issue and the fix!
THE FIX
