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;
    }
};
相关推荐
herinspace26 分钟前
管家婆实用贴-如何分离和附加数据库
开发语言·前端·javascript·数据库·语音识别
ILYT NCTR1 小时前
搭建Golang gRPC环境:protoc、protoc-gen-go 和 protoc-gen-go-grpc 工具安装教程
开发语言·后端·golang
叶小鸡1 小时前
小鸡玩算法-力扣HOT100-堆
数据结构·算法·leetcode
小雅痞1 小时前
[Java][Leetcode simple] 28. 找出字符串中第一个匹配项的下标
java·开发语言·leetcode
likerhood1 小时前
java中的不可变类(Immutable)
java·开发语言
Ulyanov1 小时前
《PySide6 GUI开发指南:QML核心与实践》 第一篇:GUI新纪元——QML与PySide6生态系统全景
开发语言·python·qt·qml·雷达电子对抗
何陋轩2 小时前
【重磅】悟空来了:国产AI编程助手深度测评,能否吊打Copilot?
人工智能·算法·面试
Rust研习社2 小时前
从入门到实践:Rust 异步编程完全指南
开发语言·后端·rust
yaoxin5211232 小时前
389. Java IO API - 获取文件名
java·开发语言·python
逸风尊者2 小时前
XGBoost模型工程使用
java·后端·算法