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;
    }
};
相关推荐
汉克老师3 小时前
CSP-J 2026 第二轮入门组真题解析(第一题 、旅游)
c++·csp-j·信息学竞赛·小学生学c++
xiaoye-duck3 小时前
《C++ 项目:手写大模型接入 SDK》Gemini接口设计(上):初始化、全量响应实现和测试
开发语言·网络·c++·语言模型
文丑颜不良啊3 小时前
LeetCode1941~1960题目解析
java·leetcode
nice_lcj5206 小时前
Java Lambda 表达式入门:怎么写、怎么用、常用方法有哪些
java·开发语言·后端·面试
码农小河666 小时前
基于SSM+JSP+MySQL的在线医疗服务系统的设计与实现
java·开发语言·mysql
老师我太想进步了20267 小时前
【数据结构-4】算法美学之顺序表
数据结构·算法
风影同志783247 小时前
编码器是激活函数吗?—— 一个看起来很像、其实不是的类比
算法
UIU1147 小时前
P1481 魔族密码
c++·算法·动态规划
文丑颜不良啊8 小时前
LeetCode1961~1980题目解析
java·leetcode
文丑颜不良啊8 小时前
LeetCode2001~2020题目解析
java·leetcode