ง่าย 0 ข้อที่แก้แล้ว อัตราผ่าน 0%

Power of Two

Check whether a number is a power of two.

สิ่งที่คุณจะได้เรียนรู้

  • Check powers of two by repeated halving
  • Use the n & (n - 1) bit trick
  • Handle zero and negative numbers

โจทย์

ดูฉบับแปล

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¹⁸

ตัวอย่าง

ตัวอย่างที่ 1
อินพุต:
n = 64

ผลลัพธ์ที่คาดหวัง:
expected = True
อินพุต:
long long n = 64;

ผลลัพธ์ที่คาดหวัง:
bool expected = true;
อินพุต:
long n = 64;

ผลลัพธ์ที่คาดหวัง:
bool expected = true;

คำอธิบาย

64 = 2⁶.

ตัวอย่างที่ 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 กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

เรียนรู้จากคนอื่น

แนวทางจากชุมชน

ยังไม่มีวิธีทำที่เผยแพร่ ลองแก้โจทย์นี้เพื่อแชร์วิธีแรก