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;
    }
};
相关推荐
Hwang2528 小时前
Attention-04-decoder部分
算法
Dlrb12118 小时前
数据结构-队列,循环队列,哈希表
数据结构·哈希表·队列·循环队列·哈希存储
计算机安禾8 小时前
【算法分析与设计】第13篇:最小生成树:Prim算法与Kruskal算法的比较研究
大数据·人工智能·算法
@大迁世界8 小时前
AI还替不了的JS能力
开发语言·前端·javascript·人工智能·ecmascript
ZJH__GO8 小时前
java项目-流水线线程池
java·开发语言
放逐者-保持本心,方可放逐8 小时前
Go + WebAssembly 构建树木数据统计分析系统
开发语言·golang·wasm·javascipt
vortex58 小时前
国密(商用密码)算法核心参数速查
算法·密码学
ftpeak9 小时前
深入浅出 LoongSuite Python Agent:让你的 AI 应用「透明化」(下篇)
开发语言·人工智能·ai·ai编程·ai开发
cany10009 小时前
C++ -- lambda捕获
c++
希望永不加班9 小时前
SpringBoot 消息幂等性设计:防重复消费
java·开发语言·spring boot·后端·spring