Skip to content

Instantly share code, notes, and snippets.

@mmloveaa
Last active October 24, 2018 09:36
Show Gist options
  • Save mmloveaa/5c1766755ee4e74acefd to your computer and use it in GitHub Desktop.
Save mmloveaa/5c1766755ee4e74acefd to your computer and use it in GitHub Desktop.
3-22 Count the holes
24 -> 1
1264 -> 2
9899 -> 5
349 -> x
You swiftly determine that the puzzle can be solved by counting the number of holes in the digits of a number. e.g. 1,2,3,5,7 have no holes, 0, 4, 6, 9 have 1 hole each, and 8 has 2 holes. 2 is therefore the value of x to the last line.
Excited by this discovery, you now want to solve this puzzle using a computer program. You have to complete the function solvePuzzle(num) where num is the input number, and the return value is the number of holes in num.
Constraints:
1 ≤ num ≤ 109
There will be no leading zeroes.
Input Format:
The function "solvePuzzle" contains an integer "num".
Output Format:
Return an integer denoting number of holes present in "num".
Sample Input #00:
num = 630
Sample Output #00:
2
Explanation #00:
6 and 0 have one hole each
Sample Input #01:
num = 1288
Sample Output #01:
4
Explanation #01:
Both 8's contain 2 holes each.
YOUR ANSWER
Javascript
function solvePuzzle(num) {
var digits = num.toString().split('');
var values =[1,0,0,0,1,0,1,0,2,1]
return digits.reduce(function(sum, digit) {
return sum + values[digit];
}, 0);
//Switch method
// return digits.reduce(function(sum, digit) {
// var value;
// switch(digit) {
// case '0':
// case'4':
// case '6':
// case '9':
// value = 1;
// case '8':
// value = 2;
// }
// }
// return sum + value;
// }, 0)
// Explanation
// return digits.reduce(function(sum, digit) {
// var value;
// if(digit == 0) {
// }
// return sum + value;
// }, 0)
// 0 1 2 3 4 5 6 7 8 9
// 1 0 0 0 1 0 1 0 2 1
}
solvePuzzle(630)
@rgabo
Copy link

rgabo commented Oct 24, 2018

To all candidates in the middle of a HackerRank coding challenge:

Please don't disqualify yourself by copypasting a solution from a GitHub gist.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment