I was given this problem which gives you 2 integers n
and m
, n
representing the number of figures of the second number, and the second number is a binary number. For example:
n= 2
m= 11
After figuring out the binary number, you have to get that number to be 0. You are only allowed to substract 1 from the binary or divide by two. For example, in this case it would be:
3->2->1 so the result is 2 since there were 2 operations made
My program does work and displays the binary number and the number of operations. But when given big numbers, it throws floating point exception. My theory is that it is because int
s are too short. But when I change them to long
s, it throws a completely inaccurate result.
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n, m, g, l, f, x, k, w;
cin >> n >> m;
g = pow(10, n);
k = pow(2, n - 1);
for (int i = 1; i <= n; i++)
{
l = m % g;
f = l / (g / 10);
if (f == 1)
{
x += k;
}
k /= 2;
g /= 10;
}
cout << x << endl;
while (x != 1)
{
if (x % 2 == 0)
{
x /= 2;
}
else
{
x -= 1;
}
w++;
}
cout << w;
return 0;
}