Offer to come, dig friends take it! I am participating in the 2022 Spring Recruit series activities – click on the task to see the details of the activities.
A, the title
Given a non-negative integer num, repeatedly add the digits in each bit until the result is a single digit. Returns the result.
The sample1Enter num =38Output:2Explanation: The process of adding the members is:38 --> 3 + 8 --> 11
11 --> 1 + 1 --> 2Due to the2Is one digit, so return2. The sample2Enter num =0Output:0
Copy the code
Thought analysis
Idea 1
-
So the first thing that comes to mind is recursion, and every time you recurse, you get a new value, and the way you do this is you cut it up, you add it up, and if it’s less than 10, you return, and if it’s more than 10, you keep recursing
-
Then you look at example 2 and think that if the first value is less than 10, return directly
-
Reducer is superimposed here, which has four parameters, respectively
The pre accumulator
The current value cur
Index Current index
Array arr
Idea 2
- If the value is greater than 10, take the first value, divide by 10, and take the remainder of the second value
- Add them and compare them, and then recurse
Idea 3
- Diminishing train of thought
- I want to add the two digits until the last digit is in the ones place,
- If the units digit of a two-digit array is 0, then the sum of the two digits must be the units digit
- Use the while loop, num>= 10
- We then start adding two digits internally, define a new value of 0 outside of the while where num>0,
- Mod, plus the initial value of the new value defined, and then round, so num is still greater than zero,
- Enter the while loop again, now superimposing the remainder and integer of the first time, and enter the while again because it is greater than 0
- All the way to zero,
- If num>0, sum will be the last ones digit. If num>=10, sum will be returned
This idea comes from the official solution of leetCode
code
Idea 1
let addDigits = function(num) {
if(num < 10) {
return num
} else {
let newNum = num.toString().split(' ').reduce((pre, cur) = > Number(pre) + Number(cur))
if(newNum >= 10) {
return addDigits(newNum)
} else {
return newNum
}
}
}
Copy the code
Idea 2
let addDigits = function(num) {
if(num>=10) {
let first = Math.floor(num/10)
let last = num % 10
console.log(pre, n)
if (first + last >= 10) {
return addDigits((pre+n))
}else {
return first + last
}
}
return num
}
Copy the code
Idea 3
while(num >= 10 ) {
let sum = 0
while (num > 0) {
sum += num % 10
console.log(sum)
num = Math.floor(num/10)
console.log(num)
}
num = sum
}
return num
Copy the code