返回

[Leetcode]258. Add Digits(C++)

题目描述

题目链接:258. Add Digits

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

例子

Input: 38 Output: 2 Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.

Follow Up

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

解题思路

简单地通过循环相加各个位直到最终 num < 9 即可,代码如下:

class Solution {
public:
    int addDigits(int num) {
        int result = 0;
        while (num > 9) {
            int next_num = 0;
            while (num > 0) {
                next_num += (num % 10);
                num /= 10;
            }
            num = next_num;
        }
        return num;
    }
};
  • 时间复杂度: O(n)
  • 空间复杂度: O(1)

GitHub 代码同步地址: 258.AddDigits.cpp

其他题目: GitHub: Leetcode-C++-Solution 博客: Leetcode-Solutions

Built with Hugo
Theme Stack designed by Jimmy