โจทย์
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.
เงื่อนไข
-10¹⁸ ≤ n ≤ 10¹⁸
ตัวอย่าง
อินพุต:
n = 64
ผลลัพธ์ที่คาดหวัง:
expected = True
อินพุต:
long long n = 64;
ผลลัพธ์ที่คาดหวัง:
bool expected = true;
อินพุต:
long n = 64;
ผลลัพธ์ที่คาดหวัง:
bool expected = true;
คำอธิบาย
64 = 2⁶.
อินพุต:
n = 12
ผลลัพธ์ที่คาดหวัง:
expected = False
อินพุต:
long long n = 12;
ผลลัพธ์ที่คาดหวัง:
bool expected = false;
อินพุต:
long n = 12;
ผลลัพธ์ที่คาดหวัง:
bool expected = false;
คำอธิบาย
12 = 4 × 3 has an odd factor, so it is not a power of two.
แนวทางการแก้
ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ
คำใบ้ 1
A power of two has exactly one bit set in binary.
คำใบ้ 2
Check that the number is positive before using a bit-based test.
คำใบ้ 3
Negative numbers and zero are never powers of two.
ความซับซ้อนที่คาดหวัง
O(1) time, O(1) extra space
แหล่งอ้างอิง
โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน