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;
    }
};
相关推荐
宇卿.2 分钟前
C#语句:
开发语言·c#
ComPDFKit4 分钟前
用 ComPDF DocSlight 提取 PDF 表格:三种样本实测与 Python 接入
开发语言·python·pdf·pdf表格提取
alphaTao6 分钟前
LeetCode 每日一题 2026/10/5-2026/10/11
算法·leetcode
liliangcsdn11 分钟前
现金流指标的探索和分析
大数据·算法
蜗牛互联网15 分钟前
Java Agent 工具调用的 allowlist、参数校验与调用预算
java·开发语言·人工智能·后端·oracle
大文说跨境16 分钟前
多账号环境隔离方案技术选型:指纹浏览器、VPS 与云手机的三种架构对比
java·开发语言·前端
chenbingjie_c18 分钟前
手撕 C++ priority_queue:二叉堆 + 模板仿函数 + 模板特化(保姆级逐函数拆解)
开发语言·c++
wang090721 分钟前
硬着头皮学数据结构和算法之Myers算法
数据结构·算法
ttwuai28 分钟前
Go后台管理系统开源项目有哪些?如何按交付形态筛掉不合适的仓库
开发语言·golang·开源
蓝悦无人机33 分钟前
无人机系列之飞控算法:从PID到AI,飞行控制的核心进化
人工智能·算法·无人机·飞控系统