From 4706c076e2f67c0c80403d71ef7f909a059b2b74 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=94=90=E6=A0=91=E6=A3=AE?= <14021051@buaa.edu.cn> Date: Sat, 29 Sep 2018 23:43:43 +0800 Subject: [PATCH] Create 231. Power of Two.md --- 231. Power of Two.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 231. Power of Two.md diff --git a/231. Power of Two.md b/231. Power of Two.md new file mode 100644 index 0000000..3084a99 --- /dev/null +++ b/231. Power of Two.md @@ -0,0 +1,21 @@ +# [231. Power of Two](https://leetcode.com/problems/power-of-two/description/) +# 思路 +求n是否是2的幂。 +1. 首先若n不是正数肯定直接返回false,若n为1直接返回true; +2. 若n是不为1的奇数返回false; +3. 令n = n / 2,若n=1则返回true否则返回第2步。 +# C++ +``` +class Solution { +public: + bool isPowerOfTwo(int n) { + if(n <= 0) return false; + if(n == 1) return true; + while(n > 1){ + if(n % 2 == 1) return false; + n /= 2; + } + return true; + } +}; +```