
Problem Statement
Given a positive integer n, the task is to determine how many integers within the inclusive range from 0 to n have binary representations that do not contain consecutive ones. The binary representation of a number refers to its expression in base-2 numeral system where each digit is either 0 or 1. This problem requires counting all valid numbers whose binary form adheres to the specific pattern of not having two 1s in a row.
Examples
Example 1
Input:
n = 5
Output:
5
Explanation:
Here are the non-negative integers <= 5 with their corresponding binary representations: 0 : 0 1 : 1 2 : 10 3 : 11 4 : 100 5 : 101 Among them, only integer 3 disobeys the rule (two consecutive ones) and the other 5 satisfy the rule.
Example 2
Input:
n = 1
Output:
2
Example 3
Input:
n = 2
Output:
3
Constraints
1 <= n <= 109
Approach and Intuition
Understanding the Binary constraint: The core challenge lies in checking each number's binary form within the given range for consecutive ones.
Brute Force Method:
- Iterate from
0ton. - Convert each number to its binary representation.
- Check if the binary string has any consecutive ones.
- Count those numbers which do not have consecutive ones.
- Iterate from
Optimization Insight:
- Directly checking each number up to
nis computationally expensive, especially whennis large (up to 1 billion). - An optimized approach involves using dynamic programming or bitwise manipulation to skip directly checking each number.
- Directly checking each number up to
Example Breakdown:
- For
n = 5, convert each number (0 to 5) to binary:- 0: 0 -> no ones
- 1: 1 -> single one
- 2: 10 -> one followed by zero
- 3: 11 -> consecutive ones
- 4: 100 -> one followed by two zeros
- 5: 101 -> alternating one and zero
- Among these, only the number
3fails the condition. Therefore, the count of valid numbers is5.
- For
Dynamic Programming Consideration:
- Utilize two arrays where one tracks the count of valid binary strings ending in
0and the other for strings ending in1. - Base cases are for single digit binary numbers.
- Transition involves building numbers using safe combinations from previous counts, avoiding direct placement of ones after one.
- Utilize two arrays where one tracks the count of valid binary strings ending in
By applying the above considerations, the solution can be both efficient and accurate, thus solving the problem within the constraints provided.
Solutions
- Java
public class Solution {
public int countValidNumbers(int n) {
int[] fibonacci = new int[32];
fibonacci[0] = 1;
fibonacci[1] = 2;
for (int index = 2; index < fibonacci.length; index++)
fibonacci[index] = fibonacci[index - 1] + fibonacci[index - 2];
int i = 30, result = 0, lastBit = 0;
while (i >= 0) {
if ((n & (1 << i)) != 0) {
result += fibonacci[i];
if (lastBit == 1) {
result--;
break;
}
lastBit = 1;
} else
lastBit = 0;
i--;
}
return result + 1;
}
}
The solution provided in Java tackles the problem of counting valid numbers up to 'n' that do not have consecutive ones in their binary representation. Here is how this solution operates:
- An array called
fibonacciis initialized to represent the number of valid binary numbers up to a certain number of digits based on the Fibonacci sequence. The size of the array is specified byint[32]assuming a 32-bit integer. - The Fibonacci sequence is pertinent because the count of valid binary numbers without consecutive ones closely follows this sequence. Each position
indexinfibonacciis calculated as the sum of the two preceding values, akin to the Fibonacci sequence (fibonacci[index - 1] + fibonacci[index - 2]). - Variables
i,result, andlastBitare used to traverse the binary representation of the number from the most significant bit to the least significant bit.istarts at 30, considering up to 31 bits for an integer. - A loop then checks each bit of
nfrom the highest to the lowest:- If the
ith bit ofnis set (i.e., equals 1), theresultis incremented by the value infibonacci[i]to account for all valid numbers that can be formed with the lower bits. - A check is made for consecutive ones: if
lastBitis also 1 (indicating consecutive ones), the loop breaks after decrementing theresult(to revert the last incorrect addition). lastBitis updated based on whether the current bit is 1 or 0.
- If the
- After the loop, 1 is added to the
resultto include zero in the count of valid numbers. - Finally, the function returns the
result, which gives the number of valid non-negative integers up tonthat do not have consecutive ones in their binary representation.
This algorithm skillfully uses the properties of the Fibonacci sequence to convert the combinatorial problem into a simple computation involving checking bits and summing corresponding Fibonacci numbers. Ensure to create a test case to verify that the code input matches the expected output for accuracy in numbering various cases from 0 up to any given n.