-
[LeetCode] 258. Add DigitsLeetCode 2022. 2. 8. 10:37728x90
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
Add Digits - Easy

웬만하면 Easy 문제들은 작성하지 않으려 했는데, 풀다보니 신기하고 재밌어서 포스팅한다.
integer 형식의 수가 주어졌을때, 그 수의 자리수들을 각각더하고 다시 그 결과의 자리수들을 각각더하고.. 를 한자리수가 될때까지 반복해 나오는 결과값을 구하는 문제다.
마냥 반복문을 돌려서 값을 얻을 수 있고 생각하기도 쉬운 문제다.
처음엔 그러려 했으나,
Follow up: Could you do it without any loop/recursion in O(1) runtime?
라는 글귀를 보고 생각을 한번 더 해보고, 쭉 적어 봤다.
0 1 2 3 4 5 6 7 8 9 10 11 12 18 19 20 21 22 27 28 29 30
0 1 2 3 4 5 6 7 8 9 1 2 3 9 1 2 3 4 9 1 2 3
처음 0을 제외하고는 계속 1,2,3,4,5,6,7,8,9가 반복된다.
생각해보면 당연하다. 자리수를 더한다고 해도 결국 원래수도 이전수에서 1더해지고, 자리수도 일의자리가 이전수보다 1증가하게 될테니.. (9일 경우엔 어차피 1로 돌아가니)
따라서 원래수에서 1을 빼준 후, 9로 나눈 나머지를 구한뒤 다시 1을 더해주면 된다.
전체 풀이 코드
class Solution { public: int addDigits(int num) { if (!num) return 0; return (num-1)%9+1; } };'LeetCode' 카테고리의 다른 글
[LeetCode] 560. Subarray Sum Equals K (0) 2022.02.10 [LeetCode] 532. K-diff Pairs in an Array (0) 2022.02.09 [LeetCode] 84. Largest Rectangle in Histogram (0) 2022.01.29 [LeetCode] 211. Design Add and Search Words Data Structure (0) 2022.01.28 [LeetCode] 1305. All Elements in Two Binary Search Trees (0) 2022.01.26