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;
    }
};
相关推荐
Dxy123931021621 分钟前
Python 条件语句详解
开发语言·python
勇闯逆流河2 小时前
【数据结构】堆
c语言·数据结构·算法
jjkkzzzz2 小时前
Linux下的c/c++开发之操作Redis数据库
数据库·c++·redis
prinrf('千寻)2 小时前
MyBatis-Plus 的 updateById 方法不更新 null 值属性的问题
java·开发语言·mybatis
pystraf2 小时前
LG P9844 [ICPC 2021 Nanjing R] Paimon Segment Tree Solution
数据结构·c++·算法·线段树·洛谷
m0_555762903 小时前
Qt缓动曲线详解
开发语言·qt
Funny-Boy3 小时前
菱形继承原理
c++
飞川撸码3 小时前
【LeetCode 热题100】739:每日温度(详细解析)(Go语言版)
算法·leetcode·golang
揽你·入怀4 小时前
数据结构:ArrayList简单实现与常见操作实例详解
java·开发语言
yuhao__z4 小时前
代码随想录算法训练营第六十六天| 图论11—卡码网97. 小明逛公园,127. 骑士的攻击
算法