"Leetcode 231" Power of

Source: Internet
Author: User

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

Ideas:

If a number is 2 power, then only one of the binary strings is 1, and the rest is 0. Execute N & (n-1) to eliminate the lowest bit of a 1, if the elimination is 0, then the number is 2 power (n = = 0 | | n = =-2147483648 for special consideration).

C++:

1 classSolution {2  Public:3     BOOLIspoweroftwo (intN) {4         if(n = =0|| n = =-2147483648)5             return false;6         7n = n & (N-1);8         9         if(n = =0)Ten             return true; One         Else A             return false; -     } -};

Python:

1 classSolution:2     #@param {integer} n3     #@return {Boolean}4     defispoweroftwo (self, n):5         ifn = = 0orn = =-2147483648:6             returnFalse7         8n = N & (n-1)9         Ten         ifn = =0: One             returnTrue A         Else: -             returnFalse

"Leetcode 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.