Skip to content

Instantly share code, notes, and snippets.

@yoaquim
Last active August 29, 2015 14:01
Show Gist options
  • Save yoaquim/d0d99e36ea86617499fb to your computer and use it in GitHub Desktop.
Save yoaquim/d0d99e36ea86617499fb to your computer and use it in GitHub Desktop.
Programming Excercise
/*
Exercise:
Write a function that takes in a number N and counts
how many numbers between 1 and N (inclusive) do not
contain any digits which are ’7′.
*/
//Recursively, it comes out somewhat nice and clean:
function countNumbers(n) {
var number = n.toString();
if (n == 1) {
return 1;
}
for (var i = 0; i < number.length; i++) {
if (number[i] == '7') {
return countNumbers(n - 1);
}
}
return (countNumbers(n - 1) + 1);
}
//But this'll quickly break the stack, given a sufficiently large n.
//A better approach is iteration:
function countNumbers(n) {
var count = 0;
for (var j = 1; j <= n; j++) {
count++;
var number = j.toString();
for (var i = 0; i < number.length; i++) {
if (number[i] == '7') {
count--;
break;
}
}
}
return count;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment