this is a question which needs to be answer for a job interview, I only know how to do the following:
int x = y/2;
is there any alternatives ?
this is a question which needs to be answer for a job interview, I only know how to do the following:
int x = y/2;
is there any alternatives ?
Just to let the interviewer know that you're up for the fun:
int x = 0;
for(int i = 0; i < y; i += 2)
{
x++;
}
Of course, you'll need to do some additional stuff for a negative number, but you get the drill ;)
a << 1
is the same as a * 2
. And a >> 1
is the same as a/2
Well as Drakosha said shifting right by 1 :
int x = y >> 1;
or
multiply by 0.5:
int x = (int)(y * 0.5);
or
subtract by the value multiplied by 0.5:
int x = (int)(y - (y * 0.5));
If you don't want to use shifting of bits you could even keep on subtracting the number by 2 till you get the remainder less than 2. Keep a count of how many times you subtracted. Plain maths.
As said, you also could shift the number bitwise. The operator is >> or <<. Look this example, should make everything clear:
int x = 16;
x = x >> 1;
System.out.println(x); // prints 8