आसान 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 के लिए अनुकूलित की गई है। ऊपर दिए गए स्टेटमेंट और सीमाओं का पालन करें।

दूसरों से सीखें

समुदाय समाधान

अभी तक कोई प्रकाशित समाधान नहीं। पहला साझा करने के लिए इस चुनौती को हल करें।