LeetCode 342. Power of Four

简介: 给定一个整数 (32 位有符号整数),请编写一个函数来判断它是否是 4 的幂次方。

v2-22ee78c5f9c60017c1ff899227a57175_1440w.jpg

Description



Given an integer (signed 32 bits), write a function to check whether it is a power of 4.


Example 1:

Input: 16

Output: true


Example 2:

Input: 5

Output: false


Follow up: Could you solve it without loops/recursion?


描述



给定一个整数 (32 位有符号整数),请编写一个函数来判断它是否是 4 的幂次方。


示例 1:

输入: 16

输出: true


示例 2:

输入: 5

输出: false


进阶:

你能不使用循环或者递归来完成本题吗?


思路



  • 一个数若是 4 的幂次方,那么这个数的二进制表示只有 一个 1。
  • 并且这个数的1 出现在(从右往左) 第 1,或 3,或 5 ,或 7 ... 位。
  • 一个数 num 只有一个 1 那么,num 和 num -1 与运算为 0。
  • 1 出现在奇数位,那么次数与 1010101010101010101010101010101 与运算为 num 本身。


# -*- coding: utf-8 -*-
# @Author:             何睿
# @Create Date:        2019-04-08 16:58:04
# @Last Modified by:   何睿
# @Last Modified time: 2019-04-08 17:11:49
class Solution:
    def isPowerOfFour(self, num: 'int') -> 'bool':
        # num 数字不为零
        # num 的二级制只有一个 1
        # num 中 1 的位置出现在第 1 位,或第 3 位,或第5 ... 位
        return num != 0 and num & (
            num - 1) == 0 and num & 0b1010101010101010101010101010101 == num

源代码文件在 这里


目录
相关文章
|
Java C++
LeetCode之Power of Two
LeetCode之Power of Two
92 0
|
Java
[LeetCode]--326. Power of Three
Given an integer, write a function to determine if it is a power of three. Follow up: Could you do it without using any loop / recursion? Credits: Special thanks to @dietpepsi for addin
1096 0
[LeetCode]--231. Power of Two
Given an integer, write a function to determine if it is a power of two. Credits: Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. 如果是power of
1073 0
LeetCode 326 Power of Three(3的幂)(递归、Log函数)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50540517 翻译 给定一个整型数,写一个函数决定它是否是3的幂(翻译可能不太合适…… 跟进: 你是否可以不用任何循环或递归来完成。
760 0
LeetCode 231 Power of Two(2的幂)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50541137 翻译 给定一个整型数,写一个函数来决定它是否是2的幂。
680 0
|
5天前
|
算法 C++
【刷题】Leetcode 1609.奇偶树
这道题是我目前做过最难的题,虽然没有一遍做出来,但是参考大佬的代码,慢慢啃的感觉的真的很好。刷题继续!!!!!!
8 0