Counting holes in number

I. Problem

Given a random number, count how many holes in total. Note: the holes for each digits are listed below

  • 0: 1hole
  • 1: 0 hole
  • 2: 0 hole
  • 3: 0 hole
  • 4: 1 hole
  • 5: 0 hole
  • 6: 1 hole
  • 7: 0 hole
  • 8: 2 holes
  • 9: 1 hole

II. Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// Test
let n = getHoles(1234567)
console.log(n) // 2

n = getHoles(1)
console.log(n) // 0

n = getHoles(0)
console.log(n) // 1

n = getHoles(9)
console.log(n) // 1

n = getHoles(12)
console.log(n) // 0

n = getHoles(-14)
console.log(n) // 1


function getHoles( num ){
if(num === 0) return 1

const map = new Map([[0,1],[1,0],[2,0],[3,0],[4,1],[5,0],[6,1],[7,0],[8,2],[9,1]])
let res = 0
num = Math.abs(num)

while( num > 0 ){
let lastDigit = num % 10
res += map.get(lastDigit)
num = Math.floor(num/10)
}
return res
}

III. Complexity

  • Time: O(n)
  • Space: O(1)