【Leetcode_easy】693. Binary Number with Alternating Bits
problem
693. Binary Number with Alternating Bits
solution1:
class Solution { public: bool hasAlternatingBits(int n) { int bit = -1; while(n>0) { /* errr... if(n&1 && bit==1) return false; else if(n&1) bit = 1; if(n&1==0 && bit==0) return false; else if(n&1==0) bit = 0; */ if(n&1==1) { if(bit==1) return false; bit = 1; } else { if(bit==0) return false; bit = 0; } n >>= 1;//err. } return true; } };
solution2:
通过异或操作判断最低位是否在0/1之间转换进行。
class Solution { public: bool hasAlternatingBits(int n) { int d = (n&1); while((n&1)==d) { d ^= 1;// n >>= 1; } return n==0; } };
参考
1. Leetcode_easy_693. Binary Number with Alternating Bits;
2. Grandyang;
完
各美其美,美美与共,不和他人作比较,不对他人有期待,不批判他人,不钻牛角尖。
心正意诚,做自己该做的事情,做自己喜欢做的事情,安静做一枚有思想的技术媛。
版权声明,转载请注明出处:https://www.cnblogs.com/happyamyhope/
心正意诚,做自己该做的事情,做自己喜欢做的事情,安静做一枚有思想的技术媛。
版权声明,转载请注明出处:https://www.cnblogs.com/happyamyhope/
浙公网安备 33010602011771号