LeetCode (258) - Add Digits

Seong Oh·2022년 2월 8일

하단 Title 클릭 시 해당 문제 페이지로 이동합니다.

- Add Digits

  • Acceptance: 61.7%
  • Difficulty: Easy

문제 설명

Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.

* Follow up: Could you do it without any loop/recursion in O(1) runtime?

예시 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.

예시 2

Input: num = 0
Output: 0

문제 풀이

코드

class Solution {
    public int addDigits(int num) {

        while (num / 10 > 0) {
            int total = 0;

            while (num / 10 > 0) {
                total += num % 10;

                num /= 10;
            }
            num += total;
        }

        return num;
    }
}

0개의 댓글