Last active
August 29, 2015 14:01
-
-
Save yoaquim/d0d99e36ea86617499fb to your computer and use it in GitHub Desktop.
Programming Excercise
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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