Tutte le sfide
Facile 1 risolta 50.0% di accettazione

Power of Two

Check whether a number is a power of two.

Cosa imparerai

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

Problema

Mostra traduzione

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.

Vincoli

-10¹⁸ ≤ n ≤ 10¹⁸

Esempi

Esempio 1
Input:
n = 64

Output atteso:
expected = True
Input:
long long n = 64;

Output atteso:
bool expected = true;
Input:
long n = 64;

Output atteso:
bool expected = true;

Spiegazione

64 = 2⁶.

Esempio 2
Input:
n = 12

Output atteso:
expected = False
Input:
long long n = 12;

Output atteso:
bool expected = false;
Input:
long n = 12;

Output atteso:
bool expected = false;

Spiegazione

12 = 4 × 3 has an odd factor, so it is not a power of two.

Come affrontarlo

Prova prima da solo, poi apri un suggerimento alla volta.

Suggerimento 1

A power of two has exactly one bit set in binary.

Suggerimento 2

Check that the number is positive before using a bit-based test.

Suggerimento 3

Negative numbers and zero are never powers of two.

Complessità attesa

O(1) time, O(1) extra space

Riferimenti

Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.

La migliore soluzione superata di ogni programmatore. Le più veloci, leggere e meglio valutate stanno in alto.

# Programmatore Linguaggio Tempo Memoria Voto dell'IA Soluzione
1 HJhettory Jurash Python 980 ms - 3/5 Vedi il codice

Impara dagli altri

Soluzioni della community

Attenzione spoiler: 1 soluzione completa sotto Prova prima a risolverla da solo. Puoi comunque sbirciare il codice degli altri sviluppatori e le recensioni AI. Accedi e risolvi la sfida per partecipare alla discussione.