Leetcode-693. Binary Number with alternating bits

Source: Internet
Author: User

Question:

Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.

Solution:

Question Setting requires determining a number in the form of 101010. How can we give an algorithm with the minimum complexity?

First, let's take a look at the basic tools to solve this question using python.

Speaking of binary, the first thing that comes to mind is the bitwise operator number. The Python bitwise operator numbers include ~ |>><<.

First look at the shift, it is easy to find that if you move 101010 to the right, there will be 10101, the sum of the two is 111111; When 111111 to 1, it will get 0 with its own and the operation

Try to write the problem-solving Code as follows:

ClassSolution: defHasalternatingbits (self, n): Return (n + (n> 1) & (n + (n> 1) + 1) = 0
Submission result: accepted

 

Leetcode-693. Binary Number with alternating bits

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.