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;
    }
};
相关推荐
sali-tec7 分钟前
C# 基于OpenCv的视觉工作流-章62-线线距离
图像处理·人工智能·opencv·算法·计算机视觉
赏金术士20 分钟前
Kotlin 从入门到进阶 之作用域函数 & 优雅写法(五)
android·开发语言·kotlin
openKaka_31 分钟前
从 scheduleUpdateOnFiber 到 Root 微任务调度:React 如何把更新交给调度系统
开发语言·前端·javascript
WolfGang00732139 分钟前
代码随想录算法训练营 Day53 | 图论 part11
算法·图论
呃呃本42 分钟前
算法题(图论)
算法·图论
梦梦代码精1 小时前
《企业开源商城选型:商业闭环、二次开发与成本平衡》
java·开发语言·低代码·开源·github
前进的李工1 小时前
智能Agent实战指南:记忆组件嵌入技巧(记忆)
开发语言·前端·javascript·python·langchain·agent
一只数据集1 小时前
商超上货人形机器人全身运控数据集分析——Kuavo 5机器人5W型号夹爪末端执行器操作轨迹数据
人工智能·算法·机器人
蜡笔小马1 小时前
03.C++设计模式-原型模式
c++·设计模式·原型模式
神仙别闹1 小时前
基于QT(C++)实现线性表的建立、插入、删除、查找等基本操作
java·c++·qt