Skip to content

Instantly share code, notes, and snippets.

@wperron
Created August 1, 2022 13:17
Show Gist options
  • Save wperron/c2f90cd15ea95b45d135263e24b4ad3b to your computer and use it in GitHub Desktop.
Save wperron/c2f90cd15ea95b45d135263e24b4ad3b to your computer and use it in GitHub Desktop.
Get the number of ones in all positive integers less than or equal to N
fn main() {
println!("{}", number_of_ones(14));
}
/// Given an integer n, count the total number of 1 digits appearing in all non-negative integers less than or equal to n.
///
/// Example:
///
/// ```bash
/// > numberOfOnes(14)
/// > 7 // 1, 10, 11, 12, 13, 14
/// ```
fn number_of_ones(n: usize) -> usize {
let mut o = 0;
for i in 1..n + 1 {
o += ones(i);
}
o
}
fn ones(mut n: usize) -> usize {
let mut ones = 0;
while n > 0 {
let digit = n % 10;
n = n / 10;
if digit == 1 {
ones += 1;
}
}
ones
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment