给定一个非负整数 n ,请问是否存在一个 x 满足 ,如果有,则返回 true ,否则返回 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