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;
    }
};
相关推荐
冷雨夜中漫步14 分钟前
Claude Code源码分析——Claude Code Agent Loop 详细设计文档
java·开发语言·人工智能·ai
麦兜和小可的舅舅14 分钟前
ClickHouse 列管理机制解析:从 COW、IColumn 到 CRTP
c++·clickhouse
超龄编码人17 分钟前
Qt Widgets Designer QTabWidget无法添加布局
开发语言·qt
北顾笙98017 分钟前
day38-数据结构力扣
数据结构·算法·leetcode
m0_6294947318 分钟前
LeetCode 热题 100-----14.合并区间
数据结构·算法·leetcode
直奔標竿20 分钟前
Java开发者AI转型第二十六课!Spring AI 个人知识库实战(五)——联网搜索增强实战
java·开发语言·人工智能·spring boot·后端·spring
xin_nai22 分钟前
LeetCode热题100(Java)(5)普通数组
算法·leetcode·职场和发展
Python大数据分析@26 分钟前
CLI一键采集,使用Python搭建TikTok电商爬虫Agent
开发语言·爬虫·python
旖-旎33 分钟前
深搜练习(组合)(5)
c++·算法·深度优先·力扣
vegetablesssss34 分钟前
vtk镜像图
c++·qt·vtk