Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.
Example 1:
Input: num = 38
Output: 2
Explanation: The process is
38 --> 3 + 8 --> 11
11 --> 1 + 1 --> 2
Since 2 has only one digit, return it.
Example 2:
Input: num = 0
Output: 0
Constraints:
- 0 <= num <= 231 - 1
이번 문제는 주어진 정수의 모든 자릿수를 더하는 것을 반복하여 한 자릿수가 나온다면 해당 숫자를 반환하는 문제이다.
/**
* @param {number} num
* @return {number}
*/
var addDigits = function(num) {
while(num >= 10){
let val = 0;
let temp = num;
while(temp >= 1){
val += temp % 10;
temp = parseInt(temp/10);
}
num = val;
}
return num
};
위 코드와 같이 간단하게 각 자리의 숫자를 더하고 이를 num에 초기화 시켜주고 이를 반복하면 된다.
'algorithm > problems' 카테고리의 다른 글
[프로그래머스 / C++] 모음 사전 (0) | 2023.05.18 |
---|---|
[프로그래머스 / C++] 피로도 (0) | 2023.05.17 |
[백준]1107번 리모컨 (0) | 2022.11.26 |
[백준] 1072번 Z _ Node_js (0) | 2022.11.21 |
[백준] 1003번 피보나치 함수 _ Node.js (0) | 2022.11.20 |