标签:数组 时间 inter 程序 比较 32位 des false value
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
标签:数组 时间 inter 程序 比较 32位 des false value
原文地址:https://www.cnblogs.com/boris1221/p/9295820.html