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;
    }
};
相关推荐
君义_noip9 分钟前
信息学奥赛一本通 4150:【GESP2509七级】⾦币收集 | 洛谷 P14078 [GESP202509 七级] 金币收集
c++·算法·gesp·信息学奥赛·csp-s
Ricky_Theseus15 分钟前
静态链接与动态链接
c++
南 阳16 分钟前
Python从入门到精通day64
开发语言·python
摸个小yu18 分钟前
【力扣LeetCode热题h100】链表、二叉树
算法·leetcode·链表
汀、人工智能24 分钟前
[特殊字符] 第93课:太平洋大西洋水流问题
数据结构·算法·数据库架构·图论·bfs·太平洋大西洋水流问题
花千树-01035 分钟前
Java 接入多家大模型 API 实战对比
java·开发语言·人工智能·ai·langchain·ai编程
ZPC821036 分钟前
rviz2 仿真控制器与真实机器人切换
人工智能·算法·机器人
澈20742 分钟前
双指针,数组去重
c++·算法
小辉同志1 小时前
207. 课程表
c++·算法·力扣·图论
CheerWWW1 小时前
深入理解计算机系统——位运算、树状数组
笔记·学习·算法·计算机系统