1. Binary String Inspection
Intuition
Format the integer into a binary string. Loop through index 1 to length - 1. If s[i] == s[i - 1], return false. If loop finishes with no violations, return true.
When to apply: Prototype validation or quick checks where speed is non-critical.
Algorithm
- Step 1: Convert n to binary string.
- Step 2: Loop i from 1 to length - 1.
- Step 3: If string[i] == string[i - 1], return false.
- Step 4: Return true if all adjacent pairs alternate.
#include <iostream>#include <string>#include <bitset> using namespace std; bool hasAlternatingBitsBrute(int n) { string s = ""; while (n > 0) { s += (n % 2 == 0 ? '0' : '1'); n /= 2; } for (int i = 1; i < (int)s.length(); ++i) { if (s[i] == s[i - 1]) return false; } return true;} int main() { cout << boolalpha; cout << "Brute (5): " << hasAlternatingBitsBrute(5) << endl; // true cout << "Brute (7): " << hasAlternatingBitsBrute(7) << endl; // false cout << "Brute (11): " << hasAlternatingBitsBrute(11) << endl; // false return 0;}Time & Space Complexity
- Time complexity:
O(log n) - Space complexity:
O(log n)