본문 바로가기
Computer Science/알고리즘

leetcode 258) Add Digits

by eeeun:) 2022. 2. 8.
반응형

LV. Easy 😎

https://leetcode.com/problems/add-digits/

 

Add Digits - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

문제

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 <= 2^31 - 1

 

문제 해결법

10으로 나눈 몫이 0일 때까지 계속 돌려주는 것을 계속 반복하면 끝!

 

해결 코드
class Solution {
public:
	int addDigits(int num) {
		int n = 0;
		while (num / 10 != 0) {
			n += num % 10;
			num = num / 10;
			if (num < 10) {
				num = n + num;
				n = 0;
			}
		}
		return num;
	}
};

728x90

댓글