Thursday 13 August 2015

Toggle nth bit


If nth bit of a number is 0, then make it as 1, else 0.
public class ToggleNthBit {

 public static int toggleNthBit(int num, int n) {
  num = num ^ (1 << n);
  return num;
 }
}


Following is the junit test case for above application.

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class ToggleNthBitTest {

 @Test
 public void test1() {
  assertEquals(ToggleNthBit.toggleNthBit(171, 0), 170);
  assertEquals(ToggleNthBit.toggleNthBit(170, 6), 234);
  assertEquals(ToggleNthBit.toggleNthBit(234, 3), 226);
  assertEquals(ToggleNthBit.toggleNthBit(226, 7), 98);
 }
}



No comments:

Post a Comment