-4

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 ?

user3730244
  • 101
  • 1
  • 1
  • 5
  • 12
    Shifting bits... Really, you should already know this, if you're interviewing for a job. – Robert Harvey Aug 08 '14 at 17:55
  • can you explain a little more on this ? – user3730244 Aug 08 '14 at 17:56
  • 1
    Even a cursory google search should give you [Division by two](http://en.wikipedia.org/wiki/Division_by_two), and very little more work will give you language specific implementations. – azurefrog Aug 08 '14 at 18:00
  • 2
    Trick question! You need to know the type of `y` :). – dlf Aug 08 '14 at 18:01
  • @dlf Good point, making bit shifting questionable! –  Aug 08 '14 at 18:36
  • 1
    Relevant? http://stackoverflow.com/questions/10681375/which-is-better-option-to-use-for-dividing-an-integer-number-by-2 By the way, how I found that was by Googling "divide number by two C++" – chris Aug 08 '14 at 18:45

6 Answers6

11

Shift right by 1 bit:

int x = y >> 1;
Drakosha
  • 11,925
  • 4
  • 39
  • 52
3

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 ;)

KodingKid
  • 971
  • 9
  • 14
1

a << 1 is the same as a * 2. And a >> 1 is the same as a/2

Academia
  • 3,984
  • 6
  • 32
  • 49
  • 3
    Not if `a` is negative (assuming C++). – T.C. Aug 08 '14 at 18:05
  • The unsigned right shift operator ">>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension. – Academia Aug 08 '14 at 18:16
1

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));
gkrls
  • 2,618
  • 2
  • 15
  • 29
0

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.

Sandeep B
  • 765
  • 1
  • 6
  • 19
0

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
BAERUS
  • 4,009
  • 3
  • 24
  • 39