# Number of Digit One in C++

C++Server Side ProgrammingProgramming

Suppose we have a number n, We have to count the total number of digit 1 appearing in all non-negative numbers less than or equal to n. So if the input is 15, then the output will be 8, because the numbers containing 1 is [1,10,11,12,13,14,15], there are 8 1s.

To solve this, we will follow these steps −

• ret := 0

• for initializing i := 1, when i <= n, i = i * 10 do −

• a := n / i, b := n mod i, x := a mod 10

• if x is same as 1, then,

• ret = ret + (a / 10) * i + (b + 1)

• Otherwise when x is same as 0, then −

• ret = ret + (a / 10) * i

• Otherwise

• ret = ret + (a / 10 + 1) * i

• return ret

## Example

Let us see the following implementation to get better understanding −

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int countDigitOne(int n) {
int ret = 0;
for(long long int i = 1; i <= n; i*= (long long int)10){
int a = n / i;
int b = n % i;
int x = a % 10;
if(x ==1){
ret += (a / 10) * i + (b + 1);
}
else if(x == 0){
ret += (a / 10) * i;
} else {
ret += (a / 10 + 1) *i;
}
}
return ret;
}
};
main(){
Solution ob;
cout << (ob.countDigitOne(15));
}

## Input

15

## Output

8
Published on 27-May-2020 05:31:02