Leetcode 342. Power of Four

Source: Internet
Author: User

Given an Integer (signed), write a function to check whether it is a power of 4.

Example: Given num = +, return true. Given num = 5, return false.

followup: Could solve it without loops/recursion?

Main topic:

Given an integer (32-bit signed), the Write function determines whether it is a power of 4.

Test with For example a topic description.

think further: can you solve the problem without looping/recursion?

Problem Solving Ideas:

If an integer is a power of 4, then the second binary form (only one 1, 0 on odd digits) has the following characteristics:

1. The highest bit is 1 and the remaining bits are 0

2.0 is an even number

Condition 1 can be judged with num & (num-1) = = 0

Condition 2 can be judged with num & 0x55555555 > 0, (0x55555555) <==> 1010101010101010101010101010101, if the obtained number is itself, You can be sure that it is 4 of the number of times:

1 classSolution {2  Public:3     BOOLIspoweroffour (intnum) {4         if(num<=0)return false;5         Else return((num& (num-1))==0) && (num&0x55555555)==num);6     }7};

Using the Loop method:

1 classSolution {2  Public:3     BOOLIspoweroffour (intnum) {
if (num < 0) return false;4 intNumofone =0;5 while(num > 0) {6 if(Num &1)7numofone++;8 if(Num >>1) &1)9 return false;TenNum >>=2; One } A if(Numofone = =1) - return true; - Else the return false; - } -};

Leetcode 342. Power of Four

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.