Skip to content

Instantly share code, notes, and snippets.

@jordinebot
Created August 3, 2022 08:50
Show Gist options
  • Save jordinebot/ba96737412b775d8245667134fcf33d6 to your computer and use it in GitHub Desktop.
Save jordinebot/ba96737412b775d8245667134fcf33d6 to your computer and use it in GitHub Desktop.
Cassidoo's Interview question of the week
/*
* Given an integer n, count the total number of 1 digits appearing in all non-negative integers less than or equal to n.
*
* > numberOfOnes(14)
* > 7 // 1, 10, 11, 12, 13, 14
*
*/
function numberOfOnes(n) {
return [...Array(n + 1).keys()].reduce(
(ones, current) => ones + (current.toString().split("1").length - 1)
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment