Pepperminttt
Pepperminttt's Dev
Pepperminttt
전체 방문자
오늘
어제
  • devInfo (86)
    • forBeingGoodDeveloper (2)
    • React (2)
      • LostArk Open API (1)
    • algorithm (58)
      • problems (44)
      • theory (14)
    • computerScience (8)
      • network (8)
    • javaScript (8)
    • Java (4)
    • web (2)
      • webApplication (2)
    • etc. (1)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 백준
  • 탐욕법 문제
  • dfs
  • 탐욕법
  • node.js
  • JavaScript
  • DP
  • bfs문제
  • 그래프
  • solved.ac
  • 프로그래머스
  • C++
  • Network
  • 벨만-포드
  • greedy
  • Java
  • BFS
  • 알고리즘
  • DP문제
  • dfs문제

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
Pepperminttt

Pepperminttt's Dev

[LeetCode] 258. Add Digits
algorithm/problems

[LeetCode] 258. Add Digits

2023. 4. 26. 16:39

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
    'algorithm/problems' 카테고리의 다른 글
    • [프로그래머스 / C++] 모음 사전
    • [프로그래머스 / C++] 피로도
    • [백준]1107번 리모컨
    • [백준] 1072번 Z _ Node_js
    Pepperminttt
    Pepperminttt
    HTML, JavaScript, Python 등 Computer language TIL

    티스토리툴바