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;
    }
};
相关推荐
张李浩2 小时前
Leetcode 054螺旋矩阵 采用方向数组解决
算法·leetcode·矩阵
big_rabbit05023 小时前
[算法][力扣101]对称二叉树
数据结构·算法·leetcode
WolfGang0073213 小时前
代码随想录算法训练营 Day11 | 二叉树 part01
数据结构
美好的事情能不能发生在我身上3 小时前
Hot100中的:贪心专题
java·数据结构·算法
myloveasuka3 小时前
Java与C++多态访问成员变量/方法 对比
java·开发语言·c++
2301_821700533 小时前
C++编译期多态实现
开发语言·c++·算法
奥地利落榜美术生灬3 小时前
c++ 锁相关(mutex 等)
开发语言·c++
xixihaha13244 小时前
C++与FPGA协同设计
开发语言·c++·算法
重庆小透明4 小时前
【java基础篇】详解BigDecimal
java·开发语言
ID_180079054734 小时前
模拟1688商品详情的Python API实现,返回符合风格的JSON数据
开发语言·python·json