0
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();

        int x = 1010110;
        System.out.println("the ith bit is " + ithBit(x, n));
    }

    public static int ithBit(int x, int n) {
        int bitValue = (x & (1 << (n - 1))) != 0 ? 1 : 0;
        return bitValue;
    }

in number 1010110, its giving 4th bit=1,6th bit=1, 7th bit=0

PaulMcKenzie
  • 34,698
  • 4
  • 24
  • 45

1 Answers1

0

This presumes the low order bit is the 0th bit. You don't need to use the conditional operator (?:). Just shift the result back and return the 1 or 0 directly. >>> is used to not backfill the sign bit, if detected, when shifting right. Otherwise, you would get -1 for ithBit(-1, 31);

public static int ithBit(int x, int n) {
        return  (x & (1 << n)) >>> n;
}
WJS
  • 36,363
  • 4
  • 24
  • 39