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;
    }
};
相关推荐
im_AMBER2 分钟前
Leetcode 147 零钱兑换 | 单词拆分
javascript·学习·算法·leetcode·动态规划
明月(Alioo)7 分钟前
Python 并发编程详解 - Java 开发者视角
java·开发语言·python
zl_vslam17 分钟前
SLAM中的非线性优-3D图优化之IMU预积分SE3推导(二十一)
人工智能·算法·计算机视觉·3d
JAVA+C语言18 分钟前
C++ STL map 系列全方位解析
开发语言·c++
c++逐梦人19 分钟前
DFS经典例题(八皇后,数独)
算法·蓝桥杯·深度优先
福赖19 分钟前
《C#反射机制》
开发语言·c#
进击的小头20 分钟前
第18篇:PID参数整定与裕度优化的现场调试实战
python·算法
cpp_250123 分钟前
P1796 汤姆斯的天堂梦
数据结构·c++·算法·题解·洛谷·线性dp
凌波粒28 分钟前
LeetCode--19.删除链表的倒数第 N 个结点(链表)
java·算法·leetcode·链表