Back to Programming Languages forum
Stuck on problem #81. Language: C++. Input using: cin. Data type: int32_t (for 32 bit integers) Can't take input for negative numbers, the program only outputs the correct number of bits upto the point the number it encounters are all positive, there is no output for and after the first negative input. Please help :(
Hi. I recently came across that problem. I solved it by casting the input numbers to unsigned integers. I don't exactly know why it worked though ^^'
Edit: I've read it again. It could be the initial size of your read buffer. Firstly, get the input with fgets
, then use strtok
to slize it into tokens and turn them to integers with sscanf
.
Hi Friend!
One funny thing you may note that in many languages "shift right" operator comes in two forms - arithmetic and logical. They differ in how the highest bit is filled after shift. Try this example
int32_t a = -1;
a >>= 1;
cout << a;
a >>= 1;
a >>= 1;
a >>= 1;
cout << a;
Unpleasant thing is that C++ (probably) lacks "logic" shift so you may need nullify highest bit manually after shift.
Other approach as kittyaurel
suggests is to treat value as unsigned (if the language allows it).
The whole idea of this problem, anyway, is to make us acquainted with machine binary representation and bit operations, which may be queer in some languages. So don't get frustrated :)
Hope this helps!
Thanks a lot @kittyaurel and @Rodion! I will try and keep the input in unsigned variables and see if that works! Also didn't know about the second type of shift right operator, should read up on that ^_^ Thanks once again!
EDIT: Declaring the input as an unsigned int works!