zoukankan      html  css  js  c++  java
  • LeetCode--231--2的幂函

    问题描述:

    给定一个整数,编写一个函数来判断它是否是 2 的幂次方。

    示例 1:

    输入: 1
    输出: true
    解释: 2

    0

     = 1

    示例 2:

    输入: 16
    输出: true
    解释: 2

    4

     = 16

    示例 3:

    输入: 218
    输出: false

    方法1:

     1 import math
     2 class Solution(object):
     3     def isPowerOfTwo(self, n):
     4         """
     5         :type n: int
     6         :rtype: bool
     7         """
     8         if n % 2 != 0 and n != 1 or n < 0 :
     9             return False
    10         width = int((math.sqrt(n)))
    11         for i in range(width+2):
    12             if math.pow(2,i) == n:
    13                 return True
    14             elif math.pow(2,i) > n:
    15                 return False
    16         return False

    方法2:二进制

     1 class Solution(object):
     2     def isPowerOfTwo(self, n):
     3         """
     4         :type n: int
     5         :rtype: bool
     6         """
     7         if n <= 0:
     8             return False
     9 
    10         return bin(n).count('1') == 1

    方法3:

    1 class Solution(object):
    2     def isPowerOfTwo(self, n):
    3         """
    4         :type n: int
    5         :rtype: bool
    6         """
    7         while n%2 == 0 and n>1:
    8             n = n/2
    9         return (n==1)

    2018-09-20 06:58:15

  • 相关阅读:
    sparse用法matlab官方说明
    C++双向循环链表
    循环链表以及迭代器的使用c++
    顺序队列c++
    顺序栈c++
    尾插法链表
    邻接表建立图
    深度优先搜索树与广度优先搜索树
    tensorflow-笔记02
    深度学习-框架介绍
  • 原文地址:https://www.cnblogs.com/NPC-assange/p/9678655.html
Copyright © 2011-2022 走看看