-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
90 lines (81 loc) · 1.8 KB
/
main.cpp
File metadata and controls
90 lines (81 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// Source: https://leetcode.com/problems/power-of-two
// Title: Power of Two
// Difficulty: Easy
// Author: Mu Yang <http://muyang.pro>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Given an integer `n`, return `true` if it is a power of two. Otherwise, return `false`.
//
// An integer `n` is a power of two, if there exists an integer `x` such that `n == 2^x`.
//
// **Example 1:**
//
// ```
// Input: n = 1
// Output: true
// Explanation: 2^0 = 1
// ```
//
// **Example 2:**
//
// ```
// Input: n = 16
// Output: true
// Explanation: 2^4 = 16
// ```
//
// **Example 3:**
//
// ```
// Input: n = 3
// Output: false
// ```
//
// **Constraints:**
//
// - `-2^31 <= n <= 2^31 - 1`
//
// **Follow up:** Could you solve it without loops/recursion?
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <bit>
#include <cstdint>
#include <cstdlib>
using namespace std;
// Use Loop
class Solution {
public:
bool isPowerOfTwo(int n) {
if (n <= 0) return false;
for (; n > 1; n >>= 1) {
if (n & 1) return false;
}
return true;
}
};
// n & -n get the right most 1-bit
class Solution2 {
public:
bool isPowerOfTwo(int n) { //
return (n > 0) ? (n & (-n)) == n : false;
}
};
// n & (n-1) removes right most 1-bit
class Solution3 {
public:
bool isPowerOfTwo(int n) { //
return (n > 0) ? (n & (n - 1)) == 0 : false;
}
};
class Solution4 {
public:
bool isPowerOfTwo(int n) { //
return (n > 0) ? popcount(static_cast<uint32_t>(n)) == 1 : false;
}
};
// Equal to (n & (n - 1)) == 0
class Solution5 {
public:
bool isPowerOfTwo(int n) { //
return (n > 0) ? has_single_bit(static_cast<uint32_t>(n)) : false;
}
};