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;
    }
};
相关推荐
爱玩亚索的程序员12 小时前
算法入门(三)学会用matplotlib画图
算法·matplotlib
請你喝杯Java12 小时前
Python 后端开发:从虚拟环境、pip、requirements.txt 到项目启动
开发语言·python·pip
一叶落43812 小时前
LeetCode 6. Z 字形变换(C语言详解)
c语言·数据结构·算法·leetcode
啊董dong12 小时前
noi-2026年3月17号作业
数据结构·c++·算法
也曾看到过繁星12 小时前
初识c++
开发语言·c++
2401_8747325312 小时前
泛型编程与STL设计思想
开发语言·c++·算法
飞Link12 小时前
具身智能中 Wrapper 架构的深度解构与 Python 实战
开发语言·python·架构
季远迩12 小时前
54.螺旋矩阵(中等)
算法
今儿敲了吗12 小时前
44| 汉诺塔问题
数据结构·c++·笔记·学习·算法·深度优先
yuyuzururu12 小时前
进程通信实验报告
c++