Python Leetcode diary--231. Power of

Source: Internet
Author: User

Topic:

Given an integer, write a function to determine if it is a power of.

class solution (Object):     def ispoweroftwo (self, N):         #        """         : Type n:int        : Rtype:bool        " " "


Methods: Analyze the characteristics of power of 2, found that 2 of any number of squares, into the binary system only the first is 1 the remaining bits 0, so my solution is as follows:

class solution (Object):     def ispoweroftwo (self, N):         return if Else if bin (n). Count ('1'else False)

The bin function converts a given number into a binary, which is returned as a string, so it is only possible to check the return value of the bin if it contains a ' 1 '.

Decomposing the line of code above to see

class solution (Object):     def ispoweroftwo (self, N):         if n<0:            return  False        returnif bin (n). Count ('1'else False


Then see the other solution is mainly n& (n-1) ==0, this method is also the use of the power of the 2 side of the characteristics, n if the power of 2, then (n-1) binary number only the highest bit is 0, the remaining bits are all 1, so let n& (n-1) bitwise AND, if equal to 0, Indicates that n is a power of 2

Python Leetcode diary--231. Power of

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.