when giving input from 5 to 7 it's not working but when giving input above 7 it's working properly.
#include<iostream>
#include<math.h>
using namespace std;
int main()
{ int n;
cout <<"Decimal : ";
cin>>n;
int ans = 0;
int i=0;
while(n != 0)
{
int bit = n % 2;
ans = (bit * pow(10,i)) + ans;
n = n / 2;
i++;
}
cout << "Binary : "<< ans;
}
You can't store a binary number as a base 10 inside a 32-bit integer larger than
1111111111. (1.1 billion). And even if you increased ans be a 64-bitlong long, you couldn't get higher than 19 bits before exceeding that limit.Let's say you have a 7 digit number such as: 9999999. In binary, that would be:
100110001001011001111111. But if you interpret that as decimal, you can't assign that value into a 32-bit integer. It won't even fit into a 64-bit integer either.Use a string instead of trying to do exponent math. The string has the advantage of never overflowing.