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;
    }
};
相关推荐
巧克力男孩dd5 分钟前
Python超典型练习题(第一次作业)
开发语言·python·算法
TlSfoward12 分钟前
TLSFOWARD TLS指纹
开发语言·数据库·爬虫·搜索引擎·https·php
爱刷碗的苏泓舒14 分钟前
平方根信息滤波:矩阵推导及 GNSS 参数估计应用
线性代数·算法·矩阵·gnss·参数估计·测量平差·平方根信息滤波
闲猫1 小时前
LangChain / Core components / Models
开发语言·python·langchain
想做小南娘,发现自己是女生喵1 小时前
第 2 章 顺序表和 vector
java·数据结构·算法
ComputerInBook1 小时前
c 和 c++ 中的宏块(macro)
c语言·c++··宏块·宏指令
艾醒2 小时前
2026年第29周(7.13-7.19)AI全复盘:技术突破、行业趣闻翻车、算力服务器商业动态
人工智能·算法
AA陈超2 小时前
004 T02 - 俯视角摄像机系统 设计文档
网络·c++·ue5·虚幻引擎
雪碧聊技术2 小时前
动态规划算法—01背包问题
算法·动态规划
-银雾鸢尾-2 小时前
C#中的索引器
开发语言·c#