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;
    }
};
相关推荐
ttwuai几秒前
Go 后台清空操作日志失败,权限和无 WHERE 删除怎么排查?
开发语言·后端·golang
十铭忘11 分钟前
HMM(隐马尔可夫模型)的理解7——Baum–Welch 算法
人工智能·算法
西西弗Sisyphus13 分钟前
Qt 在无边框窗口上做一套换肤系统
开发语言·数据库·qt
西西弗Sisyphus17 分钟前
Qt 启动 UsageStatistic 插件报错
开发语言·qt
NeoGressAI外贸数字化18 分钟前
外贸独立站零询盘排查:从 Google Search Console 到 PageSpeed 的技术实操
开发语言·c++
神仙别闹24 分钟前
基于 QT(C++)实现操作系统
数据库·c++·qt
无小道26 分钟前
C/C++——异步编程小记
开发语言·c++·c++11
奇树谦26 分钟前
Pimpl 模式(d-pointer)详解:如何解决 C++ 头文件过大、编译依赖和 ABI 兼容问题
开发语言·c++
shylyly_32 分钟前
stack/queue中的deque
数据结构·c++·deque·双端队列·queue·stack·容器适配器
DevOpenClub37 分钟前
Markdown、HTML 和 PPT 如何稳定交付:文档转换任务的幂等发布流程
开发语言·前端·c#·html·powerpoint