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;
    }
};
相关推荐
红宝村村长5 分钟前
windows笔记本双系统ubuntu设置
开发语言
深圳市方中禾科技1 小时前
FZH1625 LCD 驱动芯片深度评测与实战指南
算法·led
菜鸟~noob2331 小时前
【电子战】第15篇:混合定位——TDOA/FDOA/AOA 联合【含matlab代码】
开发语言·matlab
我不会起名字3222 小时前
一天一道算法题(34):回溯法的经典例题(子集)
java·数据结构·python·算法·golang·深度优先·力扣
ThornArmor2 小时前
重铸1996|肉体渲染:关节的裂缝:分段模型积木拼装与未成熟的 RSP 矩阵骨骼动画形变
c语言·汇编·c++·python·硬件架构·游戏机
Dreams_l3 小时前
死信队列和延迟队列介绍
java·开发语言
Zenova EdgeOS3 小时前
Python 工业边缘 redis-py 异步实战
开发语言·redis·python
huang5791473 小时前
哈希算法的抗碰撞机制与安全性增强策略4
算法
林浩杨_4 小时前
SIGIR 2026|南京大学:Video-GAR:“通过生成 Query 来验证视频语义理解”的生成增强范式
论文阅读·人工智能·算法
君顾14 小时前
西安 24 小时自助健身房系统开发实战指南
java·开发语言·健身房