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;
    }
};
相关推荐
烟锁池塘柳01 分钟前
【C/C++】解决C++控制台输出中文乱码问题
c语言·开发语言·c++
:-)11 分钟前
基础算法-选择排序
数据结构·算法·排序算法
zh路西法13 分钟前
【10天速通Navigation2】(九):LQR最优控制器的原理推导与Nav2插件实现
c++·ros2·最优控制·lqr·navigation2
浮沉98717 分钟前
二分查找算法例题(一)
算法
C+-C资深大佬18 分钟前
Java 变量:从入门到精通
java·开发语言·python
辞旧 lekkk20 分钟前
【Qt系统相关】鼠标事件
linux·开发语言·qt·学习·计算机外设·萌新
退休倒计时29 分钟前
【每日一题】LeetCode 17. 电话号码的字母组合 TypeScript
算法·leetcode·typescript
chouchuang39 分钟前
day-027-面向对象-下
开发语言·python
粘稠的浆糊40 分钟前
[AtCoder - abc465_d ]X to Y题解
数据结构·c++·算法
誰能久伴不乏41 分钟前
C++11 随机数生成——告别 rand()
开发语言·c++