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;
    }
};
相关推荐
扶摇接北海1763 分钟前
洛谷:B4477 [语言月赛 202601] 考场安排
数据结构·c++·算法
武藤一雄4 分钟前
C# 中精准锁定类型信息指南:typeof vs GetType()
开发语言·windows·c#·.net·.netcore
IAUTOMOBILE5 分钟前
Qt 入门级开发实践:浅析基于 QTtest 项目的 C++ GUI 编程基础
开发语言·c++·qt
凸头7 分钟前
从聊天机器人到业务执行者:Agentic Orchestration 如何重构 Java 后端体系
java·开发语言·重构
爱丽_9 分钟前
AQS 的 `state`:volatile + CAS 如何撑起原子性与可见性
java·前端·算法
2301_7887705510 分钟前
OJ模拟5
数据结构·算法
zhuhezhang11 分钟前
一个用golang开发的文本对比工具
开发语言·后端·golang·wails
羊小猪~~13 分钟前
算法/力扣--字符串经典题目
c++·考研·算法·leetcode·职场和发展·哈希算法
攒了一袋星辰13 分钟前
10万级用户数据日更与定向推送系统的可靠性设计
java·数据库·算法
王杨游戏养站系统14 分钟前
3分钟搭建1个游戏下载站网站教程!SEO站长养站系统!
开发语言·前端·游戏·游戏下载站养站系统·游戏养站系统