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;
    }
};
相关推荐
2401_8318249612 分钟前
代码性能剖析工具
开发语言·c++·算法
是wzoi的一名用户啊~25 分钟前
【C++小游戏】2048
开发语言·c++
Sunshine for you1 小时前
C++中的职责链模式实战
开发语言·c++·算法
@我漫长的孤独流浪1 小时前
Python编程核心知识点速览
开发语言·数据库·python
qq_416018721 小时前
C++中的状态模式
开发语言·c++·算法
2401_884563241 小时前
模板代码生成工具
开发语言·c++·算法
code 小楊1 小时前
yrb 1.5.0 正式发布:Python 极简国内下载加速与全景可视化终端体验!
开发语言·python
2401_831920742 小时前
C++代码国际化支持
开发语言·c++·算法
m0_672703312 小时前
上机练习第51天
数据结构·c++·算法
ArturiaZ2 小时前
【day60】
算法·深度优先·图论