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;
    }
};
相关推荐
Figo_Cheung11 分钟前
Figo共振网络宇宙演化论(RNC) :从原初对称破缺到全息大和谐的演化路径研究
开发语言·php·量子计算
地平线开发者12 分钟前
模型量化入门:从浮点模型到低比特表示
算法
重生之我来学Python16 分钟前
Git-SVN 混合开发,从入门到精通!
开发语言·git·svn·github
CoderYanger21 分钟前
前端基础——JavaScript(基础语法)(下篇)
java·开发语言·前端·javascript·程序人生·面试·职场和发展
枫叶林FYL22 分钟前
【群体智能集群控制工程实践】第10章 无人舰队核心功能实现
大数据·人工智能·算法
京师20万禁军教头31 分钟前
39面向对象(高级)-设计模式
java·开发语言·设计模式
不会就选b40 分钟前
【无标题】
算法
m0_739312871 小时前
【自动驾驶和机器人控制】万向锁(Gimbal Lock)原理详解 + 和欧拉角 / 四元数 / SO(3)对比
算法·机器人·自动驾驶
白山编程大哥1 小时前
Java 迭代器接口详解:从 Iterator 到 ListIterator 的完整指南
java·开发语言·windows
见叶之秋1 小时前
【C++】String类的使用(含模拟实现)
java·开发语言·c++