231. Power of Two

LeetCode easy original: C# #bit-manipulation #csharp #easy #leetcode
Task text is translated from Russian for the selected interface language. Code is left unchanged.

given integer n, return true, если оно является степенью двойки. В противном случае return false.

integer n является степенью двойки, если существует integer x, такое что n == 2^x.

Example

Input: n = 1

Output: true

Explanation: 2^0 = 1

C# solution

matched/original
public class Solution {
    public bool IsPowerOfTwo(int n) {
        if (n == 0) return false;
        long x = n;
        return (x & (-x)) == x;
    }
}

C++ solution

auto-draft, review before submit
#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

matched/original
class Solution {
    public boolean isPowerOfTwo(int n) {
        if (n == 0) return false;
        long x = n;
        return (x & -x) == x;
    }
}

JavaScript solution

matched/original
class Solution {
    isPowerOfTwo(n) {
        if (n === 0) return false
        let x = BigInt(n)
        return (x & -x) === x
    }
}

Python solution

matched/original
class Solution:
    def isPowerOfTwo(self, n: int) -> bool:
        if n == 0:
            return False
        return (n & -n) == n

Go solution

matched/original
func 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

Active vacancies with overlapping task tags are shown.

All vacancies
There are no active vacancies yet.