Google Interview Question
Software Engineer / DevelopersCountry: United States
int i = -1;
i = i >>> 1;
//This will shift the singed bit to right by 1 and hence making the value 2147483647
We need logical right shift here, so >>> is correct. Otherwise, the arithmetic right shift >> would always yield -1.
The best way to get the max value of int on 32 or 64 bit processors is by negating the 0(so that we get all 1's) and then doing an unsigned right shift (>>> in java).
int c = (~0) >>> 1;
In C, if we do normal shift (~0 >> 1), the compiler will perform arithmetic shift and will append the sign bit into the shifted bit. Instead, we would have to force a logical shift by explicitly declaring the value as unsigned, i.e. by doing something like this:
~0u >> 1;
def max_int():
import struct
max_int_list = [1] * (struct.calcsize("i")*8)
max_int_list[0] = 0 # highest priorty bit is reserved for negative flag
max_int_str = "".join(str(x) for x in max_int_list)
print(max_int_str)
return int(max_int_str,2)
AD's answer is perfect. Here is a bit of explanation:
Imagine you have a signed 4 bit system. In that system
-1
would be this:
1111
||_ from here bits are inverted
|_ sign bit (negative)
Shift to right add a zero to beggining of sequence:
0111
||_ regular bits. all 1 from here (max value)
|_ sign bit (positive)
#include <limits.h>
#include <stdio.h>
int main()
{
/* find the position of the most significant bit */
int msb_pos = (sizeof(int) * CHAR_BIT) - 1;
/* Move number 1 to the MSB pos and then take xor with -1 */
int result = (1 << msb_pos) ^ -1;
printf("Result = %d\n", result);
printf("Builtin = %d\n", INT_MAX);
return result;
}
I read in a book that the effect of >> on a signed int is undefined. That is, different compilers generated different types of code. Thus, I can up with this code.
#include <limits.h>
#include <stdio.h>
int main()
{
/* find the most significant bit (MSB) pos */
int msb_pos = (sizeof(int) * CHAR_BIT) - 1;
/* mov number 1 to the MSB pos and then xor with -1 */
int result = (1 << msb_pos) ^ -1;
printf("Result = %d\n", result);
printf("Builtin = %d\n", INT_MAX);
return result;
}
#include <stdio.h>
int add(int i, int j)
{
int sum = i ^ j;
int carry = i & j;
while(carry != 0){
carry = carry << 1;
i = sum;
j = carry;
sum = i ^ j;
carry = i & j;
}
return sum;
}
int multiply(int i, int j){
int result = 0;
while(j != 0)
{
if(j & 01)
{
result = add(result, i);
}
i <<= 1;
j >>= 1;
}
return result;
}
int get()
{
int size = sizeof(int);
unsigned int ret = 1;
int i = 1;
while(true){
if(i == 31)
return (int)(ret | (1 << size));
i = add(i, 1);
ret <<= 1;
ret |= 1;
}
}
int main()
{
printf("%d\n", get());
}
private int maxInt()
- Vir Pratap Uttam April 30, 2015{
int a=-1;
a=a>>>1;
return a;
}