zoukankan      html  css  js  c++  java
  • 693. Binary Number with Alternating Bits

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

    Example 1:

    Input: 5
    Output: True
    Explanation:
    The binary representation of 5 is: 101
    

    Example 2:

    Input: 7
    Output: False
    Explanation:
    The binary representation of 7 is: 111.
    

    Example 3:

    Input: 11
    Output: False
    Explanation:
    The binary representation of 11 is: 1011.
    

    Example 4:

    Input: 10
    Output: True
    Explanation:
    The binary representation of 10 is: 1010.


    判断一个数的二进制中,01是否是交替出现的

    C++(3ms):
     1 class Solution {
     2 public:
     3     bool hasAlternatingBits(int n) {
     4         int t1 , t2 ;
     5         t1 = n%2 ;
     6         n/=2 ;
     7         while(n){
     8           t2 = n%2 ;
     9           n/=2 ;
    10           if (t2 == t1)
    11               return false ;
    12           t1 = t2 ;
    13         }
    14         return true ;
    15     }
    16 };

    C++(3ms):

     1 class Solution {
     2 public:
     3     bool hasAlternatingBits(int n) {
     4         int d = n&1 ;
     5         while((n&1) == d){
     6             d = 1-d ;
     7             n >>= 1 ;
     8         }
     9         return n == 0 ;
    10     }
    11 };

    java(14ms):

     1 class Solution {
     2     public boolean hasAlternatingBits(int n) {
     3         int d = n&1 ;
     4         while((n&1) == d){
     5             d = 1-d ;
     6             n >>= 1 ;
     7         }
     8         return n == 0 ;
     9     }
    10 }
     
  • 相关阅读:
    squid反向代理
    LVM逻辑卷管理
    磁盘分区
    磁盘阵列
    apache基本配置
    LNMP简要配置
    高性能Web服务器Nginx
    samba文件共享服务配置(multiuser机制)二 (共两节)
    samba文件共享服务配置一(共2节)
    linux 批量修改文件名 文件名只保留部分,去掉部分
  • 原文地址:https://www.cnblogs.com/mengchunchen/p/7802804.html
Copyright © 2011-2022 走看看