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
LeetCode 326: 3 的幂 LeetCode 342: 4 的幂 时间复杂度:O(1) 只需要使用常数次位运算和布尔运算 空间复杂度:O(1) 只需要使用常数个额外变量即可 代码(Python3) class Solution: def isPowerOfTwo(self, n: int) -> bool: # 非正数一定不是 2 的幂次方 if n <= 0: return False return (n ...
【LeetCode】Power of Two 问题描写叙述 Given an integer, write a function to determine if it is a power of two. 意:推断一个数是否是2的n次幂 算法思想 假设一个数小于或等于0。一定不是2的幂次数 假设一个大于0且数是2的n次幂,则其的二进制形式有且仅有一个1,反之成立。 算法实现 publicclassS...
Leetcode链接: power-of-two/ 问题描述和例子:输入整数n, 判断是否为2的次方形成的数。 算法分析: 1.迭代法,不断除以2,结果是否等于1,如果是,返回True,否则False。 2. 数学法:输入范围为 2^{31}-1 , 如果一…
Leetcode上有种解法,就是让n&n-1,假设n仅仅含有一个1那么结果就是零。 简单解法: classSolution{public:boolisPowerOfTwo(intn){if(n<=0)returnfalse;intcount=0;while(n!=0){if(n%2!=0){count++;}n=n>>1;if(count>1)returnfalse;}returntrue;}}; ...
LeetCode Top Interview Questions 231. Power of Two (Java版; Easy) 题目描述 Given an integer, write a function to determine if it is a power of two. Example 1: Input: 1 Output: true Explanation: 20 = 1 Example 2: Input: 16
题目地址:https://leetcode.com/problems/reordered-power-of-2/description/题目描述:Starting with a positive 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 in a way such that ...
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的幂。
Breadcrumbs leetcode-daily /231-power-of-two / 231-power-of-two.java Latest commit HistoryHistory File metadata and controls Code Blame 9 lines (9 loc) · 168 Bytes Raw 1 2 3 4 5 6 7 8 9 class Solution { public boolean isPowerOfTwo(int n) { long x = n; if(x==0){ return...
[LeetCode] Power of Two, Power of Three, Power of Four 三道基本相同的题目,都可以用位操作、递归和迭代来做。 Power of Two 1. Bit Manipulation -- 2 ms beats 21.88% 2. Iteration -- 2 ms beats 21.88% Power of Three 1. Recursion -- 20 ms beats 24% 2. Iteration -- 15-17 ms ...