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;
    }
};
相关推荐
炸膛坦客9 分钟前
C++ 学习与 CLion 使用:(四)常量和变量,包括字面常量和符号常量
开发语言·c++·学习
特立独行的猫a17 分钟前
C/C++三方库移植到HarmonyOS平台详细教程(补充版so库和头文件形式)
c语言·c++·harmonyos·napi·三方库·aki
java1234_小锋39 分钟前
说说你对Integer缓存的理解?
java·开发语言
至此流年莫相忘1 小时前
TypeReference 泛型的使用场景及具体使用流程
java·开发语言·spring boot
windSnowLi1 小时前
Python opencv识别图片中重叠圆的圆心位置
开发语言·python·opencv
zh_xuan1 小时前
LeeCode 40.组合总和II
c语言·数据结构·算法
都叫我大帅哥2 小时前
动态规划:从懵逼到装逼,一篇让你彻底搞懂DP的终极指南
java·算法
wangluoqi2 小时前
c++ 数据结构-并查集、ST表 小总结
数据结构·c++
艾莉丝努力练剑3 小时前
《递归与迭代:从斐波那契到汉诺塔的算法精髓》
c语言·学习·算法
王廷胡_白嫖帝3 小时前
Qt网络速度测试工具开发教程 - 从零开始构建网络测速应用
开发语言·网络·qt