Đề bài
Decide whether n equals 2ᵏ for some whole number k ≥ 0 (1, 2, 4, 8, …).
Implement is_power_of_two(n).
Input
n: The number to check.
Output
Return true if n is a power of two.
Ràng buộc
-10¹⁸ ≤ n ≤ 10¹⁸
Ví dụ
Đầu vào:
n = 64
Kết quả mong đợi:
expected = True
Đầu vào:
long long n = 64;
Kết quả mong đợi:
bool expected = true;
Đầu vào:
long n = 64;
Kết quả mong đợi:
bool expected = true;
Giải thích
64 = 2⁶.
Đầu vào:
n = 12
Kết quả mong đợi:
expected = False
Đầu vào:
long long n = 12;
Kết quả mong đợi:
bool expected = false;
Đầu vào:
long n = 12;
Kết quả mong đợi:
bool expected = false;
Giải thích
12 = 4 × 3 has an odd factor, so it is not a power of two.
Hướng tiếp cận
Hãy tự thử trước, sau đó mở từng gợi ý một.
Gợi ý 1
A power of two has exactly one bit set in binary.
Gợi ý 2
Check that the number is positive before using a bit-based test.
Gợi ý 3
Negative numbers and zero are never powers of two.
Độ phức tạp mong đợi
O(1) time, O(1) extra space
Tham khảo
Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.