> For the complete documentation index, see [llms.txt](https://dfine.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://dfine.gitbook.io/leetcode/258.add_digits.md).

# 258.Add Digits

**258.Add Digits**

难度:Easy

> 给定一个非负整数 num，反复将各个位上的数字相加，直到结果为一位数。

示例: 输入: 38 输出: 2 解释: 各位相加的过程为：3 + 8 = 11, 1 + 1 = 2。 由于 2 是一位数，所以返回 2。 进阶: 你可以不使用循环或者递归，且在 O(1) 时间复杂度内解决这个问题吗？

方法：最直接的就是循环相加，代码如下：

```
class Solution {
public:
    int addDigits(int num) {
        int res;
        while(num>9)
        {
            res=num%10;
            while(num>0)
            {
                num=num/10;
                res+=num%10;
            }
            num=res;
        }
        return res;
    }
};
```

方法2：使用归纳法列出数列的前面一些项，可以发现总是从1-9再循环，因此可以发现规律。

```
class Solution {
public:
    int addDigits(int num) {
        if(!num) return 0;
        int t=num%9;
        return t?t:9;
    }
};
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://dfine.gitbook.io/leetcode/258.add_digits.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
