diff --git a/README.md b/README.md index 46021cf..3e156a9 100644 --- a/README.md +++ b/README.md @@ -247,7 +247,7 @@ My LeetCode solutions with Chinese explanation. 我的LeetCode中文题解。 | 337 |[House Robber III](https://leetcode.com/problems/house-robber-iii/)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/337.%20House%20Robber%20III.md)|Medium| | | 338 |[Counting Bits](https://leetcode.com/problems/counting-bits/)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/338.%20Counting%20Bits.md)|Medium| | | 341 |[Flatten Nested List Iterator](https://leetcode.com/problems/flatten-nested-list-iterator/)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/341.%20Flatten%20Nested%20List%20Iterator.md)|Medium| | -| 342 |[Power of Four](https://leetcode.com/problems/power-of-four)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/342.%20Power%20of%20Four.md)|Easy| | +| 342 |[Power of Four](https://leetcode.com/problems/power-of-four)|[C++](solutions/342.%20Power%20of%20Four.md)|Easy| | | 343 |[Integer Break](https://leetcode.com/problems/integer-break/)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/343.%20Integer%20Break.md)|Medium| | | 344 |[Reverse String](https://leetcode.com/problems/reverse-string)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/344.%20Reverse%20String.md)|Easy| | | 345 |[Reverse Vowels of a String](https://leetcode.com/problems/reverse-vowels-of-a-string)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/345.%20Reverse%20Vowels%20of%20a%20String.md)|Easy| | diff --git a/solutions/342. Power of Four.md b/solutions/342. Power of Four.md index 3102dba..0a0333c 100644 --- a/solutions/342. Power of Four.md +++ b/solutions/342. Power of Four.md @@ -14,15 +14,20 @@ 第1个条件等价于去掉最后的那个1后整个数变为0,即 `num & (num - 1) == 0`;(**注意学习这种去掉二进制最后一个1的方法**) 第2个条件等价于 `(num | mask) == mask`, 其中`mask = 0b01010101010101010101010101010101`。 -## 思路二 -还是基于思路一的两个条件,我们知道如果只满足思路一的条件1的数可能是2^n也可能是4^n, 怎样排除掉2^n呢? -我们知道: - -所以, -* 1.n为偶数时既是2的幂也是4的幂,此时(-1)^n==1所以(2^n-1)% 3==0; -* 2.n为奇数是只是2的幂但不是4的幂, 此时(-1)^n=-1所以(2^n-1)% 3==1; -故可以用(2^n-1)% 3是否等于0来等价判断思路一的条件2, 将2的幂和4的幂区分开。 +## 思路二 +还是基于思路一的两个条件,我们知道如果只满足思路一的条件1的数可能是`2^n`也可能是`4^n`, 怎样排除掉`2^n`呢? +我们知道: +
+ +
+ +所以, + +* 1.n为偶数时既是2的幂也是4的幂,此时`(-1)^n==1`所以`(2^n - 1)% 3==0`; +* 2.n为奇数是只是2的幂但不是4的幂, 此时`(-1)^n=-1`所以`(2^n - 1)% 3==1`; + +故可以用`(2^n-1)% 3`是否等于0来等价判断思路一的条件2, 将2的幂和4的幂区分开。 # C++ ## 思路一 ``` C++ diff --git a/solutions/img/342.png b/solutions/img/342.png new file mode 100644 index 0000000..93ea970 Binary files /dev/null and b/solutions/img/342.png differ