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;
    }
};
相关推荐
张二娃同学7 分钟前
03_变量常量与输入输出_printf与scanf详解
算法
JAVA面经实录91719 分钟前
Java集合大全终极手册(一)
java·开发语言
信竞星球_少儿编程题库25 分钟前
2026年全国信息素养大赛算法应用主题赛 丝路新城 C++ 模拟卷(三)
开发语言·c++
Zhang~Ling35 分钟前
深入解析C++list:从0到1实现一个完整的链表类
c++·链表·list
千里马-horse1 小时前
gRPC -- Java 基础教程
java·开发语言·grpc
甲方大人请饶命1 小时前
Java-面向对象进阶(qqbb知识点)
java·开发语言
ChoSeitaku1 小时前
07_static_JavaBean_继承_super/this
java·开发语言
江南十四行1 小时前
并发编程(一)
java·jvm·算法
hbugs0011 小时前
EVE-NG桥接外网的5种方式
开发语言·网络·php·eve-ng·rstp·流量洞察
z200509301 小时前
今日算法(依旧二叉树)
算法·leetcode·职场和发展