正常情况:先将n转化为二进制字符串,然后判断此字符串中的1的个数,如果n是2的幂次方,那么1的个数只可能有一个,即此二进制字符串中1的第一次出现的位置和最后一次出现的位置相等。 publicbooleanisPowerOfTwo3(intn){if(n<1) {returnfalse; }Stringstr=Integer.toBinaryString(n);returnstr.indexOf("1")...
publicclassSolution{publicbooleanisPowerOfTwo(intn){if(n<=0)returnfalse;inti =0;intcountBit =0;while(i <32){if((n&(1<<i))!=0) countBit++; i++; }if(countBit !=1)returnfalse;returntrue; } } 算法时间 T(n)=O(1) 演示结果 publicstaticvoidmain(String [] args){intn =4; Solu...
[LeetCode] Power of Two Given an integer, write a function to determine if it is a power of two. 这道题没啥难度。主要是搞清楚怎么来判断一个数是不是power of two。 最简单的方法就是一直除以2最后等于1。如果不能,那么都是false。 ......
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
leetcode231. Power of Two 题目要求 Given an integer, write a function to determine if it is a power of two. 判断一个整数是否是2的幂。 思路和代码 当我们从二进制的角度来看,这个题目就非常简单了。其实题目的要求等价于该整数对应的二进制数中,一共有几个1。该题目的难点在于考虑边界情况,比如-2...
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
Leetcode力扣1418 手画图解版|点菜展示表 Display table of food order in restaurant 爱学习的饲养员 2442 1 Leetcode 231 2的幂 书森学院 65 1 Leetcode力扣239.滑动窗口最大值 丶mars_ 3481 3 Leetcode 231. Power of Two (Python) Myron_yoo 21 0 Leetcode刷题 2 两数相加 Add Two Numbers...
就是判断一个数是不是2的次方数。 代码如下: public class Solution { public boolean isPowerOfTwo(int n) { if(n<=0) return false; n = n&(n-1); return n==0 ?true:false; } } 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. ...
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的幂。
Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two. For example: "112358" is an additive number because the digits can form an additive sequence: 1, 1, 2, 3, 5, 8. 代码语言:javascript 代码运行次数:0 运行 复制 1 + 1 ...