231. Power of Two
Le texte du problème est traduit du russe pour la langue sélectionnée. Le code reste inchangé.
given entier n, return true, если оно является степенью двойки. В противном случае return false.
entier n является степенью двойки, если существует entier x, такое что n == 2^x.
Exemple
Input: n = 1
Output: true
Explanation: 2^0 = 1
C# solution
correspondant/originalpublic class Solution {
public bool IsPowerOfTwo(int n) {
if (n == 0) return false;
long x = n;
return (x & (-x)) == x;
}
}
C++ solution
brouillon automatique, à relire avant soumission#include <bits/stdc++.h>
using namespace std;
// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
public bool IsPowerOfTwo(int n) {
if (n == 0) return false;
long x = n;
return (x & (-x)) == x;
}
}
Java solution
correspondant/originalclass Solution {
public boolean isPowerOfTwo(int n) {
if (n == 0) return false;
long x = n;
return (x & -x) == x;
}
}
JavaScript solution
correspondant/originalclass Solution {
isPowerOfTwo(n) {
if (n === 0) return false
let x = BigInt(n)
return (x & -x) === x
}
}
Python solution
correspondant/originalclass Solution:
def isPowerOfTwo(self, n: int) -> bool:
if n == 0:
return False
return (n & -n) == n
Go solution
correspondant/originalfunc isPowerOfTwo(n int) bool {
if n == 0 {
return false
}
x := int64(n)
return (x & -x) == x
}
Algorithm
Проверка на ноль: Если n равно нулю, return false, так как ноль не является степенью двойки.
Преобразование к длинному типу: Преобразуйте n к типу long, чтобы избежать переполнения при выполнении побитовых операций.
Побитовая проверка: Используйте побитовую операцию, чтобы проверить, является ли number степенью двойки. number является степенью двойки, если результат выражения (x & (-x)) равен x.
😎
Vacancies for this task
offres actives with overlapping task tags are affichés.
Il n'y a pas encore d'offres actives.