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;
    }
};
相关推荐
虚拟搬运工20 分钟前
Python类及元类的创建流程
开发语言·chrome·python
Code哈哈笑32 分钟前
【C++ 学习】多态的基础和原理(10)
java·c++·学习
Aurora_th39 分钟前
树与图的深度优先遍历(dfs的图论中的应用)
c++·算法·深度优先·图论·dfs·树的直径
消失的旧时光-194339 分钟前
kotlin的密封类
android·开发语言·kotlin
A_cot43 分钟前
Redis 的三个并发问题及解决方案(面试题)
java·开发语言·数据库·redis·mybatis
学步_技术43 分钟前
Python编码系列—Python原型模式:深克隆与高效复制的艺术
开发语言·python·原型模式
alden_ygq1 小时前
GCP容器镜像仓库使用
java·开发语言
苹果酱05671 小时前
一文读懂SpringCLoud
java·开发语言·spring boot·后端·中间件
Eoneanyna1 小时前
QT设置git仓库
开发语言·git·qt
小鹿( ﹡ˆoˆ﹡ )1 小时前
Python中的树与图:构建复杂数据结构的艺术
开发语言·python