# The Weekly Challenge 126: Count Numbers (C++ Solutions)

Part 1 of The Weekly Challenge 126: You are given a positive integer \$N. Write a script to print count of numbers from 1 to \$N that don’t contain digit 1.

```#include <iostream>

/*
* You are given a positive integer n.
* Write a script to print the count of
* numbers from 1 to n that don't contain digit the 1.
*/

class CountNumbers{
private:
int has_1(int);
int count_with_1(int);
public:
int count_without_1(int);
};

int CountNumbers::has_1(int n){
std::string s = std::to_string(n);
const char* c = s.c_str();
while(*c != '\0'){
if(*c == '1')
return 1;
c++;
}
return 0;
}

int CountNumbers::count_with_1(int n){
int count = 0;
for(int i = 1; i <= n; i++)
count += has_1(i);
return count;
}

int CountNumbers::count_without_1(int n){
return n - count_with_1(n);
}

int main(int argc, char** argv){
CountNumbers cn;
int n;
n = 15;
std::cout << cn.count_without_1(n) << std::endl;
n = 25;
std::cout << cn.count_without_1(n) << std::endl;
}
```

Example output:
```\$ g++ -o cxx/ch-1 cxx/ch-1.cxx
\$ ./cxx/ch-1
8
13
```

### Recent Posts from This Journal

• #### A Simple Binary Tree in Perl

This Binary Tree implementation uses Class::Struct and only defines find() and insert() operations, along with a simple print function for…

• #### The Weekly Challenge 127: Conflict Intervals (C++ Solutions)

Part 2 of The Weekly Challenge 127: You are given two sets with unique numbers. Write a script to figure out if they are disjoint. #include

• #### The Weekly Challenge 127: Disjoint Lists (C++ Solutions)

Part 1 of The Weekly Challenge 127: You are given two sets with unique numbers. Write a script to figure out if they are disjoint. #include

Comments for this post were disabled by the author