Thursday 13 August 2015

Set nth bit of a number

We can set nth bit of a number using  <<, | operators.

public class SetNthBit {

 public static int setNthBit(int num, int nthBit){
  num = (num | (1 << nthBit));
  return num;
 }
}

Following is the junit test case.

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class SetNthBitTest {

 @Test
 public void test1() {
  assertEquals(SetNthBit.setNthBit(42, 0), 43);
  assertEquals(SetNthBit.setNthBit(43, 2), 47);
  assertEquals(SetNthBit.setNthBit(47, 4), 63);
 }
}



No comments:

Post a Comment