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

    package LeetCode_693
    
    /**
     * 693. Binary Number with Alternating Bits
     * https://leetcode.com/problems/binary-number-with-alternating-bits/description/
     *
     * 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.
     * */
    class Solution {
        fun hasAlternatingBits(n: Int): Boolean {
            var n_ = n
            var lastBitIs1 = (n_ % 2) == 1//if odd number last bit must be 1
            while (n_ > 0) {
                n_ = n_ shr 1//because the last bit had check in below, so here need shift first
                val curBit = n_ and 1
                if (curBit == 1 && lastBitIs1) {
                    //represent last one and current one both is 1
                    return false
                } else if (curBit == 0 && !lastBitIs1) {
                    //represent last one and current one both is 0
                    return false
                }
                //check again
                lastBitIs1 = (n_ % 2) == 1
            }
            return true
        }
    }
  • 相关阅读:
    0317复利计算的回顾与总结
    0518 Scrum 项目 5.0
    0517 Scrum 项目4.0
    0512 Scrum 项目3.0
    实验三 进程调度模拟程序
    0505 Scrum 项目1.0
    0502团队项目 SCRUM团队成立
    0428 团队项目2.0
    0422团队项目
    实验二 作业调度模拟程序
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/13185538.html
Copyright © 2011-2022 走看看