For a programming contest question, I've come up with this solution:
#include <bits/stdc++.h>
using namespace std;
inline bool isBasedTwo(int n) {
while (n) {
if ((n % 10) > 1)
return false;
n /= 10;
}
return true;
}
int main() {
int n, count(0);
cin >> n;
for (int i(1); i <= n; i++)
if (isBasedTwo(i))
++count;
cout << count;
return 0;
}
The input consists of an integer 'n'. The program must count the numbers in range of 1 to n which which only consist of zeros and ones (are a binary representation).
For example for the input '10' the program must output 2 since 1 and 10 are the only numbers in the range which only consist of zero and one digits.
But this code gets "Time Limit Exceeded" error for a few test cases. My question is, is there any better approach to this problem?