---
# System prepended metadata

title: LeetCode 231. Power of Two
tags: [Leetcode]

---

---
title: 'LeetCode 231. Power of Two'
disqus: hackmd
---

# LeetCode 231. Power of Two



## Description

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

Input: n = 16
Output: true
Explanation: 2^4^ = 16

## Constraints

-2^31^ <= x <= 2^31^ - 1

## Answer

此題注意次方都是正數，故只考慮大於0的數。因2的次方在上只有一個bit有值，所以若將n對n-1取&，則必為0。若非0就不是2的次方。

```Cin=
// 2022_04_16
bool isPowerOfTwo(int n) {
    return n>0 && !(n&(n-1));
}
```



## Link
https://leetcode.com/problems/power-of-two/
###### tags: `Leetcode` 
