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;
    }
};
相关推荐
Evand J12 分钟前
MATLAB绘图函数介绍:plotmatrix绘图,附MATLAB例子
开发语言·matlab·绘图
比特 GOK14 分钟前
Qt项目ui文件中新添加的控件在代码中不识别的问题解决
开发语言·qt·ui
云天AI实战派18 分钟前
Agent 全流程实战:用 Python 搭建技能路由智能体,落地小龙虾门店运营助手
开发语言·人工智能·python
楼田莉子25 分钟前
仿Muduo的高并发服务器:LoopThread模块及其ThreadPool模块
linux·服务器·c++·后端·学习
rit843249929 分钟前
基于遗传算法的电动汽车充电站选址优化:模型与MATLAB实现
开发语言·matlab
Rust研习社32 分钟前
你为什么总是入门 Rust 失败
开发语言·后端·rust
我滴老baby1 小时前
工具调用全景解析从Function Calling到MCP协议的完整实践
开发语言·人工智能·python·架构·fastapi
小李子呢02111 小时前
前端八股JS---Map / Set / WeakMap / WeakSet
开发语言·前端·javascript
翻身的咸鱼ing1 小时前
常用代码知识
算法·深度优先·哈希算法
feifeigo1231 小时前
自适应大邻域搜索(ALNS)算法的MATLAB 实现
开发语言·算法·matlab