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;
    }
};
相关推荐
happyprince16 分钟前
03-深刻观-CodeX哲学与升华(源码)
算法·ai编程
不会打球的王子19 分钟前
Day 27:迁移学习与微调 — 站在巨人的肩膀上
算法
老当益壮梁奶奶25 分钟前
Linux软件编程学习笔记(二)Linux文件IO编程入门:从fopen到fgetc
linux·c语言·c++·笔记·学习
雪的季节30 分钟前
C++ 高级(泛型编程与模板)(有空再研究吧)
c++
三十岁老牛再出发31 分钟前
8月21日总结
c++·python
longxiaozhang632 分钟前
C#继承:让代码少写一点,偷懒的好方法
开发语言·c#
weixin_4407305044 分钟前
python+request实现接口-参数化小结
开发语言·python
CHHH_HHH1 小时前
【Linux系统篇】深入解析Linux文件系统:从磁盘寻址到软硬链接
linux·服务器·开发语言·后端·ubuntu
yngsqq1 小时前
窗体快速取消
java·开发语言
数模竞赛Paid answer1 小时前
2025年中青杯数学建模A题康养城市建设求解全过程论文及程序
算法·数学建模·数据分析·中青杯