leetcode_231 question--power of two (bitwise operations)

Source: Internet
Author: User
Tags bitwise

Power ofTotal accepted:11027 Total submissions:36750my submissions QuestionSolution

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

Credits:
Special thanks to @jianchao. Li.fighter for adding the problem and creating all test cases.

Hide TagsMath Bit ManipulationHide Similar Problems(E) Number of 1 BitsHas you met this question in a real interview? Yes No

Discuss

The problem is to calculate whether a number is a 2 of the number of times, in fact, can be converted to calculate the number of bits on how many 1, it can be, the son this can be used bit operation method, that is, with a number n and n-1 bit and operation, you can remove a 1,

It is important to note that negative numbers must not be 2 of the time.

#include <iostream>using namespace Std;bool ispoweroftwo (int n) {if (n<0) return 0;int re=0;while (n) {re++;n=n & (n-1);} if (re==1) return 1;elsereturn 0;} int main () {cout<<ispoweroftwo (6) <<endl;}

  

leetcode_231 question--power of two (bitwise operations)

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.