-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathadd-digits.js
More file actions
60 lines (55 loc) · 1.32 KB
/
add-digits.js
File metadata and controls
60 lines (55 loc) · 1.32 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// 1st Try
// Time Complexity O(n)
// Space Complexity O(1)
/**
* @param {number} num
* @return {number}
*/
var addDigits = function (num) {
if (num < 10) {
return num;
}
return addDigits(num.toString().split('').reduce((a, b) = > Number(a) + Number(b), 0));
};
// 2nd Try
// Time Complexity O(1)
// Space Complexity O(1)
/**
* @param {number} num
* @return {number}
*/
var addDigits = function (num) {
return (num - 1) % 9 + 1;
};
// 3rd Try
// Time Complexity O(n)
// Space Complexity O(1)
/**
* @param {number} num
* @return {number}
*/
var addDigits = function (num) {
var num_arr = num.toString().split('');
var ret = num_arr.reduce(function (a, b) {
return parseInt(a) + parseInt(b);
}, 0);
if (ret < 10) {
return ret;
} else {
return addDigits(ret);
}
};
/*
* Summarize
* - Pay attention to the string and number transition.
*
* - reduce (callback, initial_value)
* The reduce() method applies a function against an accumulator
* and each value of the array (from left-to-right) to reduce it to a single value.
*
* - Trick
* Tried out all the numbers between 1 to 20, found the rules:
* Results are based on multiple of 9, the answer is n%9
* However, to include number itself is a multiple of 9 situation
* The answer is (n-1)%9 + 1;
*/