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;
    }
};
相关推荐
NAGNIP3 小时前
轻松搞懂全连接神经网络结构!
人工智能·算法·面试
NAGNIP3 小时前
一文搞懂激活函数!
算法·面试
董董灿是个攻城狮3 小时前
AI 视觉连载7:传统 CV 之高斯滤波实战
算法
爱理财的程序媛9 小时前
openclaw 盯盘实践
算法
端平入洛10 小时前
auto有时不auto
c++
MobotStone12 小时前
Google发布Nano Banana 2:更快更便宜,图片生成能力全面升级
算法
颜酱16 小时前
队列练习系列:从基础到进阶的完整实现
javascript·后端·算法
用户57573033462416 小时前
两数之和:从 JSON 对象到 Map,大厂面试官到底在考察什么?
算法
程序猿追16 小时前
“马”上行动:手把手教你基于灵珠平台打造春节“全能数字管家”
算法