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;
    }
};
相关推荐
被开发耽误的大厨9 分钟前
1、==、equals、hashCode底层原理?重写场景?
算法·哈希算法
java1234_小锋12 分钟前
Java高频面试题:什么是可重入锁?
java·开发语言
WolfGang00732132 分钟前
代码随想录算法训练营 Day38 | 动态规划 part11
算法·动态规划
雾岛听蓝1 小时前
Qt操作指南:窗口组成与菜单栏
开发语言·经验分享·笔记·qt
zopple1 小时前
Laravel vs ThinkPHP:PHP框架终极对决
开发语言·php·laravel
松☆2 小时前
C++ 算法竞赛题解:P13569 [CCPC 2024 重庆站] osu!mania —— 浮点数精度陷阱与 `eps` 的深度解析
开发语言·c++·算法
耿雨飞2 小时前
Python 后端开发技术博客专栏 | 第 06 篇 描述符与属性管理 -- 理解 Python 属性访问的底层机制
开发语言·python
耿雨飞2 小时前
Python 后端开发技术博客专栏 | 第 08 篇 上下文管理器与类型系统 -- 资源管理与代码健壮性
开发语言·python
(Charon)2 小时前
【C++/Qt】C++/Qt 实现 TCP Server:支持启动监听、消息收发、日志保存
c++·qt·tcp/ip