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
This presumes the low order bit is the
0thbit. You don't need to use the conditional operator (?:). Just shift the result back and return the1or0directly.>>>is used to not backfill the sign bit, if detected, when shifting right. Otherwise, you would get-1forithBit(-1, 31);