classSolution{publicbooleanisPowerOfTwo(intx){returnx >0&& (x ==1|| (x %2==0&& isPowerOfTwo(x /2))); } } Python 实现(递归) classSolution:defisPowerOfTwo(self, x):""" :type n: int :rtype: bool """returnx >0and(x ==1o
Can you solve this real interview question? Power of Two - 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 == 2x. Example 1: Input: n = 1 Ou
*@return*/publicstaticbooleanisPowerOfTwo_2(intn){if(n <0)returnfalse;if(n ==1)returntrue;while(n >2) {if((n &1) !=0)returnfalse; n = n >>1; }returnn==2; }/** * 方法三 * <p>如果是power of two, 则2进制表达中,有且仅有一个1. 可以通过移位来数1的个数 * 这里用了...
Can you solve this real interview question? Reordered Power of 2 - You are given an integer n. We reorder the digits in any order (including the original order) such that the leading digit is not zero. Return true if and only if we can do this so that t
所以判断时候是2的幂,只要用 230 % n 是否为0即可,为0则该数是2的幂。这个怎么证明大家可以去试下,很简单的。具体代码如下: public boolean isPowerOfTwo(int n) { return n>0 && (Math.pow(2, 30) % n == 0); } 相似题目 Power of Three: 编写一个函数来判断n是否是3的幂...
class Solution: def reorderedPowerOf2(self, n: int) -> bool: # 先计算 n 的十进制位出现次数,方便后续复用 digit_to_cnt: Counter = Counter(str(n)) # 枚举所有 2 的幂次方 for i in range(31): # 如果所有十进制数位的出现次数都相同,则 n 和 1 << i 是按十进制位重排的, #则 n 满足...
Return true if and only if we can do this in a way such that the resulting number is a power of 2. Example 1: Input: 1 Output: true 1. 2. Example 2: Input: 10 Output: false 1. 2. Example 3: Input: 16 Output: true
Given an integer, write a function to determine if it is a power of two. Credits: Special thanks to@.fighterfor adding this problem and creating all test cases. Subscribeto see which companies asked this question. 2、分析 比如我们发现1、2、4、8、16转化成二进制为 ...
leetcode231. Power of Two 题目要求 Given an integer, write a function to determine if it is a power of two. 判断一个整数是否是2的幂。 思路和代码 当我们从二进制的角度来看,这个题目就非常简单了。其实题目的要求等价于该整数对应的二进制数中,一共有几个1。该题目的难点在于考虑边界情况,比如-2...
Power of Two Given an integer, write a function to determine if it is a power of two. 整除法 复杂度 时间O(1) 空间 O(1) 思路 最简单的解法,不断将原数除以2,一旦无法整除,余数不为0,则说明不是2的幂,如果整除到1,说明是2的幂。