-
Notifications
You must be signed in to change notification settings - Fork 5
/
BinaryNumberWithAlternatingBits.java
36 lines (31 loc) · 1.1 KB
/
BinaryNumberWithAlternatingBits.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/*
Problem Statement:
Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.
Problem Link:
Binary Number with Alternating Bitshttps://leetcode.com/problems/binary-number-with-alternating-bits/description/
Solution:
https://github.com/sunnypatel165/leetcode-again/blob/master/solutions/BinaryNumberWithAlternatingBits.java
Author:
Sunny Patel
https://github.com/sunnypatel165
https://www.linkedin.com/in/sunnypatel165/
*/
class Solution {
public boolean hasAlternatingBits(int n) {
return hasAlternatingBitsUsingBitWise(n);
//return hasAlternatingBitsBruteForce(n);
}
public boolean hasAlternatingBitsUsingBitWise(int n){
n = n ^ n>>1;
return (n & n+1)==0;
}
public boolean hasAlternatingBitsBruteForce(int n) {
String binary = Integer.toBinaryString(n);
for(int i =1;i<binary.length();i++){
if(binary.charAt(i)==binary.charAt(i-1))
return false;
}
return true;
}
}