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;
    }
};
相关推荐
木木子229 小时前
# 密码强度检测深度解析:正则表达式实时分析、多维度评分算法与可视化反馈
mysql·算法·华为·正则表达式·harmonyos
大圣编程10 小时前
Java 多维数组详解
java·开发语言
Sw1zzle12 小时前
算法入门(四):二叉树 - 递归遍历三件套
算法·leetcode
万法若空13 小时前
【算法-查找】查找算法
java·数据结构·算法
海石13 小时前
子树怎么找?树的3种遍历方式来帮忙!
算法·leetcode
海石13 小时前
难度分 1588:思路 + 技巧 = AC
算法·leetcode
殳翰13 小时前
下服务器端开发流程及相关工具介绍(C++)
开发语言·c++
落寞的星星14 小时前
这个对象就包含了已经转换好的DFA和各种词法分析器运转所需要的参数。下一步,我们就可以用ScannerInfo对象创建出Scanner对象,请看下面的代码:
开发语言·c#
nothing&nowhere14 小时前
用 Python 做问卷数据清洗:无效样本检测与处理实战
开发语言·python·数据清洗·数据处理·问卷星·问卷星脚本·刷问卷
青瓦梦滋14 小时前
协议定制/序列化-反序列化(Linux视角)
linux·服务器·网络·c++