Looking at links such as this and this, I understand that unsigned int
in C
should be of 16 bits. As such, the maximum value that it can store should be 32767
.
a. Why can we store INT_MAX in an int variable, such as:
int res=INT_MAX;
b. How is the code like below which calculates the power of 2
valid (runs without any error/warning):
class Solution {
public:
bool isPowerOfTwo(int n) {
return n>0 && (!(n&n-1));
}
};
because the constraints say: -2^31 <= n <= 2^31 - 1
, shouldn't we be using long
?
CodePudding user response:
a. Why can we store INT_MAX in an int variable, such as:
int res=INT_MAX;
INT_MAX
is the maximum value that can be store in int
. Per definition that can be stored in an int
.
b. How is the code like below which calculates the power of 2 valid (runs without any error/warning): ...
because the constraints say: -2^31 <= n <= 2^31 - 1, shouldn't we be using long?
The constraints are wrong. First they assume int
to be 32bit, which is not the case on e.g. AVR. Second they assume int
is two's-complement, which is only true since C 20.
It would be more accurate to say the contraints are INT_MIN <= n <= INT_MAX
. But really what is the point. The argument is int
. That already says that.
Better would be to use unsigned int
, uintmax_t
or a template. There is no reason to limit this function to int
.
Since C 20 there is std::has_single_bit
for this.