当前位置:网站首页>693. alternate bit binary number

693. alternate bit binary number

2022-06-27 05:55:00 Mr Gao

693. Alternate bit binary number

Given a positive integer , Check that its binary representation is always 0、1 Appear alternately : let me put it another way , That is, the numbers of two adjacent digits in binary representation will never be the same .

Example 1:

Input :n = 5
Output :true
explain :5 The binary representation of is :101

Example 2:

Input :n = 7
Output :false
explain :7 The binary representation of is :111.

Example 3:

Input :n = 11
Output :false
explain :11 The binary representation of is :1011.

The solution code is as follows :


bool hasAlternatingBits(int n){
    
    int pre=n%2;
    n=n/2;
    int t;
    while(n){
    
        t=n%2;
        if(t==pre){
    
            return false;
        }
        else{
    
            n=n/2;
            pre=t;
        }
    }
    return true;


}
原网站

版权声明
本文为[Mr Gao]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/178/202206270540108178.html