给定一个非负整数 n ,请问是否存在一个 x 满足 ,如果有,则返回 true ,否则返回 false
数据范围:
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param n int整型 * @return bool布尔型 */ public boolean poweroftwo (int n) { // write code here int num=1; while(num<=n){ if(num==n){ return true; }else{ num=num<<1; } } return false; } }
import java.util.*; public class Solution { public boolean poweroftwo (int n) { return n == 1 || n == 2 || n == 4 || n == 8 || n == 16 || n == 32 || n == 64 || n == 256 || n == 512 || n == 1024 // 2 ^ 10 || n == 2048 || n == 4096 || n == 8192 || n == 16384 || n == 32768 || n == 65536 || n == 131072 || n == 262144 || n == 524288 || n == 1048576 // 2 ^ 20 || n == 2097152 || n == 4194304 || n == 8388608 || n == 16777216 || n == 33554432 || n == 67108864 || n == 134217728 || n == 268435456 || n == 536870912 || n == 1073741824; // 2 ^ 30 } }说明了幂函数确实上升很快,我的只写了30行代码就完成了这个问题:)
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param n int整型 * @return bool布尔型 */ public boolean poweroftwo (int n) { // write code here if (n == 0){ return false; } while(n > 1){ if((n&1) == 1){ return false; } n = n >>> 1; } return true; } }
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param n int整型 * @return bool布尔型 */ bool poweroftwo(int n) { // write code here while(n) { if((n&1)==0)//==的优先级更高!!! { n>>=1; } else { if(n==1) { return true; } else { return false; } } } return false; } };
# -*- coding: utf-8 -*- # # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param n int整型 # @return bool布尔型 # class Solution: """ 题目: https://www.nowcoder.com/practice/4a04240fd2be4e1287aab4af067f6d8f?tpId=196&tqId=40455&rp=1&ru=/exam/oj&qru=/exam/oj&sourceUrl=%2Fexam%2Foj%3Fpage%3D8%26tab%3D%25E7%25AE%2597%25E6%25B3%2595%25E7%25AF%2587%26topicId%3D196&difficulty=undefined&judgeStatus=undefined&tags=&title= 算法: 题目求:2^x = n 当n = 0时,无解,返回False 当n = 1时,x = 0 当n > 1时: 若n % 2 == 0: n >>= 1 else: 返回False 返回True 复杂度: 时间复杂度:O(logN) 空间复杂度:O(1) """ def poweroftwo(self, n): # write code here if n == 0: return False while n > 1: if n % 2 == 0: n >>= 1 else: return False return True if __name__ == "__main__": sol = Solution() n = 4 # n = 6 res = sol.poweroftwo(n) print res
public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param n int整型 * @return bool布尔型 */ public boolean poweroftwo(int n) { // write code here double v = Math.log10(n) / Math.log10(2); int vInt = (int) v; if (vInt == v) { return true; } return false; } }