This was the problem statement.
*Complement of Base 10 Integer
The complement of an integer is the integer you get when you flip all the 0's to 1's and all the 1's to 0's in its binary representation.
For example, The integer 5 is "101" in binary and its complement is "010" which is the integer 2. Given an integer n, return its complemet*
I saw some solutions to this proble using bit masking, which is something I will get to, but first I want to know why this code given below does not work?
It works for smaller values, but for input: 299475 output: 224816 Expected Output: 224812
And the problem seems to persist for greater values.
#include <math.h>
class Solution {
#include <math.h>
public:
int bitwiseComplement(int n) {
long a = 0;
int i = 0;
if ( n == 0) {
return 1;
}
while ( n != 0 ) {
int b = n & 1;
if ( b == 1) {
b = 0;
}
else if (b == 0){
b = 1;
}
n = n >> 1;
a = a + (b * pow(10, i));
i++;
}
long sol = 0;
int k = 0;
while ( a != 0) {
int b = a % 10;
sol = sol + (b * pow(2, k));
k++;
a = a/10;
}
return sol;}
};
powfor integer-based problems. Thepowis a floating point function, and with that, you will inherit all the issues associated with floating point calculations (such as inexact results).~numberalready gives you the binary complement in one single operation... And 'base 10' is misleading if you want to calculate binary complements, as there's a base10 complement as well: 647 gets 352 – and their bit patterns are not complements in binary…int, thus you suffer from overflow (undefined behaviour for signed integers!).longon many systems (e.g. windows – in contrast to e.g. 64-bit linux) has the same size asintso wouldn't help out either, instead trylong long(or don't rely on system's sizes at all and tryuint64_tfromcstdintheader.a = a + b << i)