zoukankan      html  css  js  c++  java
  • lintcode入门篇四

    142. O(1)时间检测2的幂次

    用 O(1) 时间检测整数 n 是否是 2 的幂次。

    样例

    Example 1:
    	Input: 4
    	Output: true
    
    
    Example 2:
    	Input:  5
    	Output: false
    

    挑战

    O(1) time

    第一种方法:&的方法

    class Solution:
        """
        @param n: An integer
        @return: True or false
        """
        '''
        1.使用递归的方法来进行判断
        2.相与的方法来进行判断
        比如:16 与 15相与,因为16 二进制位10000,15减去1二进制位01111  相与>>00000
        或者 1&0 >> 0
        其他不是2的幂次的情况:
        15&14  01111 & 01110  >>01110
        '''
        def checkPowerOf2(self, n):
            # write your code here
            if n&(n-1) == 0:
                return True
            return false

    第二种方法:递归的方法

    class Solution:
        """
        @param n: An integer
        @return: True or false
        """
        def checkPowerOf2(self, n):
            # write your code here
            if n == 2 or n ==1:
                return True
            if n%2 == 1 or n == 0:
                return  False
            return self.checkPowerOf2(n//2)

    平方根,平方,立方:

    1.求平方根,int(pow(n,0.5))

    2.求平方,pow(n,2)

    3.求立方,pow(n,3)

    157. 判断字符串是否没有重复字符

    中文English

    实现一个算法确定字符串中的字符是否均唯一出现

    样例

    样例 1:

    输入:  "abc_____"
    输出:  false
    

    样例 2:

    输入:  "abc"
    输出:  true	
    

    挑战

    如果不使用额外的存储空间,你的算法该如何改变?

    class Solution:
        """
        @param: str: A string
        @return: a boolean
        """
        def isUnique(self, str):
            # write your code here
            for s in str:
                if str.count(s) !=1:
                    return False
            return  True
  • 相关阅读:
    hdoj_1556Color the ball
    wchar_t与char转换(总结)
    算法艺术——网络最大流
    poj_3268Silver Cow Party
    poj_2352Stars
    BellmanFord模板
    saas模式
    什么是管道
    什么是CMMI
    saas模式
  • 原文地址:https://www.cnblogs.com/yunxintryyoubest/p/12195522.html
Copyright © 2011-2022 走看看