You are given an integer n that contains exactly one set bit (1) in its binary representation. Find the position of that set bit. Positions are 1-based from the least-significant bit (LSB).
If the input does not contain exactly one 1 (e.g., n == 0 or has multiple ones), implementations below return 0 to indicate an invalid input unless otherwise noted.
If a number contains exactly one set bit then it is a power of two. The test n != 0 && (n & (n - 1)) == 0 verifies that property in one branch-free check. Once confirmed, the position of the set bit is the number of trailing zeros plus one (1-based). Many languages expose a fast builtin to count trailing zeros; otherwise a small loop or bit-length-based trick yields the same result.
classSolution {
public:int findSingleSetBitPos(unsignedint n) {
if (n ==0u|| (n & (n -1u)) !=0u) return0; // invalid input
// fast builtin when available
int ans = __builtin_ctz(n) +1; // defined for n != 0
return ans;
}
};
classSolution {
publicintfindSingleSetBitPos(int n) {
if (n == 0 || (n & (n - 1)) != 0) return 0;
int ans = Integer.numberOfTrailingZeros(n) + 1;
return ans;
}
}
1
2
3
4
5
6
7
classSolution:
deffind_single_set_bit_pos(self, n: int) -> int:
if n ==0or (n & (n -1)) !=0:
return0# n is power of two; position is bit_length of n (1-based) ans: int = n.bit_length()
return ans
The index of the only set bit equals the number of trailing zeros plus one. Many platforms provide an intrinsic to count trailing zero bits (often one CPU instruction) which gives pos = ctz(n) + 1.
import math
classSolution:
deffind_single_set_bit_pos_fast(self, n: int) -> int:
if n ==0or (n & (n -1)) !=0:
return0# Python 3.11+: int.bit_count available, but trailing zero helper not built-in until 3.11# Fallback: use (n & -n) to isolate lowest set bit and compute position via bit_lengthreturn (n &-n).bit_length()