LeetCode258. Add Digits

文章目录

一、题目

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 <= 231 - 1

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

二、题解

cpp 复制代码
class Solution {
public:
    int addDigits(int num) {
        while(num > 9){
            int sum = 0;
            while(num){
                sum += num % 10;
                num /= 10;
            }
            num = sum;
        }
        return num;
    }
};
相关推荐
yyy(十一月限定版)几秒前
CF2131D Arboris Contractio
算法
栈溢出了3 分钟前
VS Code Python 自动导包失效排查笔记
开发语言·笔记·python
无名猿3 分钟前
map / set 完全指南:红黑树与有序容器
数据结构·c++·性能优化·stl·标准库
朝朝辞暮i9 分钟前
C++ 第 28 课:Lambda 表达式
开发语言·c++·算法
代码什么用12 分钟前
LeetCode-560.和为 K 的子数组
算法·leetcode
Frank_refuel15 分钟前
深入理解RpcRouter(远端调用模块)
开发语言·qt
All for pursuit.17 分钟前
【回溯-3】39.组合总和
数据结构·c++·算法·leetcode
黑科技iOS上架26 分钟前
双引擎解决oc/swift开发引用加固难题
开发语言·ios·swift·审核·ios混淆·执行程序差异化
释厄62326 分钟前
BSD 基础论——不要忘记连接·不要停滞循环·AI基础算法
人工智能·算法
yujunl26 分钟前
U9客开中UI插件开发过程中碰到有一个坑
开发语言