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;
    }
};
相关推荐
chushiyunen6 分钟前
python中的内置属性 todo
开发语言·javascript·python
麦麦鸡腿堡10 分钟前
JavaWeb_请求参数,设置响应数据,分层解耦
java·开发语言·前端
2301_8194143033 分钟前
C++与区块链智能合约
开发语言·c++·算法
Zaly.39 分钟前
【Python刷题】LeetCode 1727 重新排列后的最大子矩阵
算法·leetcode·矩阵
不想看见40440 分钟前
Valid Parentheses栈和队列--力扣101算法题解笔记
开发语言·数据结构·c++
炸膛坦客43 分钟前
单片机/C/C++八股:(十五)内存对齐、结构体内存对齐
c语言·开发语言·单片机
老约家的可汗1 小时前
C/C++内存管理探秘:从内存分布到new/delete的底层原理
c语言·c++
娇娇yyyyyy1 小时前
QT编程(13): Qt 事件机制eventfilter
开发语言·qt
做怪小疯子1 小时前
蚂蚁暑期 319 笔试
算法·职场和发展
bcbobo21cn1 小时前
C# byte类型和byte数组的使用
开发语言·c#·字节数组·byte类型