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;
    }
};
相关推荐
float_com2 分钟前
LeetCode 27. 移除元素
leetcode
王老师青少年编程5 分钟前
csp信奥赛c++中的递归和递推研究
c++·算法·递归·递推·csp·信奥赛
独特的螺狮粉6 分钟前
开源鸿蒙跨平台Flutter开发:量子态波函数坍缩系统-波动力学与概率云渲染架构
开发语言·flutter·华为·架构·开源·harmonyos
冰暮流星15 分钟前
javascript之dom访问属性
开发语言·javascript·dubbo
lsx20240615 分钟前
SQL Auto Increment 自动增长
开发语言
Bczheng117 分钟前
五.serialize.h中的CDataStream类
算法·哈希算法
小O的算法实验室18 分钟前
2025年SEVC,考虑组件共享的装配混合流水车间批量流调度的多策略自适应差分进化算法,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
t1987512818 分钟前
MATLAB模糊数学模型(Fuzzy Mathematical Model)实现指南
开发语言·matlab
汀、人工智能21 分钟前
[特殊字符] 第36课:柱状图最大矩形
数据结构·算法·数据库架构·图论·bfs·柱状图最大矩形
Evand J26 分钟前
MATLAB批量保存现有绘图窗口的方法,简易方法,直接保存到当前目录,不手动设置
开发语言·matlab·教程