[leetcode] Binary Number with Alternating Bits
Posted Lin.B
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode] 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.
1 class Solution { 2 public boolean hasAlternatingBits(int n) { 3 int[] binary = new int[32]; 4 int i = 0; 5 while ( n > 0 ){ 6 binary[i++] = n % 2; 7 n = n/2; 8 } 9 for ( int j = 0 ; j < i - 1 ; j ++ ){ 10 if ( binary[j] + binary[j+1] != 1 ) return false; 11 } 12 return true; 13 } 14 }
运行时间9ms,击败97.56%。
1 class Solution { 2 public boolean hasAlternatingBits(int n) { 3 n = n ^ (n>>1); 4 return (n&(n+1) )== 0; //判断是否是全1,如果是全1, 5 } 6 }
位运算的运行时间就比较长了,16ms。不过位运算更简洁,理解了位运算也能更好理解程序。
以上是关于[leetcode] Binary Number with Alternating Bits的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode - 693. Binary Number with Alternating Bits
693. Binary Number with Alternating Bits - LeetCode
[LeetCode] Prime Number of Set Bits in Binary Representation
leetcode练习:693. Binary Number with Alternating Bits
leetcode-762-Prime Number of Set Bits in Binary Representation
Leetcode 762. Prime Number of Set Bits in Binary Representation