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;
    }
};
相关推荐
破浪前行·吴3 分钟前
数据结构概述
数据结构·学习
香蕉鼠片20 分钟前
MFC是什么
c++·mfc
码云数智-大飞34 分钟前
零基础微信小程序制作平台哪个好
开发语言
心态与习惯43 分钟前
Julia 初探,及与 C++,Java,Python 的比较
java·c++·python·julia·比较
py有趣1 小时前
力扣热门100题之不同路径
算法·leetcode
神仙别闹1 小时前
基于 MATLAB 实现的 DCT 域的信息隐藏
开发语言·matlab
_日拱一卒1 小时前
LeetCode:25K个一组翻转链表
算法·leetcode·链表
techdashen1 小时前
Go 标准库 JSON 包迎来重大升级:encoding/json/v2 实验版来了
开发语言·golang·json
啊哦呃咦唔鱼1 小时前
LeetCodehot100-394 字符串解码
算法
小欣加油1 小时前
leetcode2078 两栋颜色不同且距离最远的房子
数据结构·c++·算法·leetcode·职场和发展