-2

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?

Farahmand
  • 49
  • 1
  • 7

2 Answers2

0

may be using scanf("%d ",&n) to input n helps you solve the problem because scanf() is faster than cin in order to be able to use it you must include studio or cstudio library

another thing that may work is that you try getchar() method to get the digits of n as characters and you check if each character equals 1 or 0 otherwise the number is not binary

hope this help

Ahmed Rajab
  • 603
  • 3
  • 10
  • 28
0

You don't need to count up to n. All you have to do, is find the largest number with ones and zeros, that when interpreted as decimal, is smaller than n.

To do this, just read the input as string, iterate over the digits, and from the first place you see a digit larger than one, change the rest to '1'.

Then interpret the string as a binary number. Which is basically the number of numbers with only ones and zeros, that are smaller than it.

#include <iostream>
#include <string>

using namespace std;

int main() {
    string n; cin >> n;
    for(int i = 0 ; i < n.size() ; i++)
        if(n[i] > '1') {
            for(int j=i ; j<n.size() ; j++)
                n[j] = '1';

            break;
        }

    cout << stoi(n, nullptr, 2) << endl;
    return 0;
}
betrunken
  • 114
  • 7