|
31 | 31 | */
|
32 | 32 |
|
33 | 33 | public class _693 {
|
34 | | - public boolean hasAlternatingBits(int n) { |
35 | | - String binaryStr = Integer.toBinaryString(n); |
36 | | - for (int i = 1; i < binaryStr.length(); i++) { |
37 | | - if (binaryStr.charAt(i - 1) == binaryStr.charAt(i)) { |
38 | | - return false; |
| 34 | + public static class Solution1 { |
| 35 | + public boolean hasAlternatingBits(int n) { |
| 36 | + String binaryStr = Integer.toBinaryString(n); |
| 37 | + for (int i = 1; i < binaryStr.length(); i++) { |
| 38 | + if (binaryStr.charAt(i - 1) == binaryStr.charAt(i)) { |
| 39 | + return false; |
| 40 | + } |
39 | 41 | }
|
| 42 | + return true; |
| 43 | + } |
| 44 | + } |
| 45 | + public static class Solution2 { |
| 46 | + public boolean hasAlternatingBits_oneline(int n) { |
| 47 | + return Integer.bitCount(((n >> 1) ^ n) + 1) == 1; |
40 | 48 | }
|
41 | | - return true; |
42 | 49 | }
|
43 | 50 | }
|
0 commit comments