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;
    }
};
相关推荐
阿Y加油吧几秒前
回溯法经典难题:N 皇后问题 深度解析 + 二分查找入门(搜索插入位置)
开发语言·python
森G4 分钟前
58、最佳实践与注意事项---------多线程、竟态条件和同步
c++·qt
汀、人工智能5 分钟前
[特殊字符] 第76课:单词拆分
数据结构·算法·均值算法·前缀树·trie·单词拆分
李小枫5 分钟前
webflux接收application/x-www-form-urlencoded参数
android·java·开发语言
CheerWWW8 分钟前
C++学习笔记——箭头运算符、std::vector的使用、静态链接、动态链接
c++·笔记·学习
沐知全栈开发10 分钟前
NumPy 字节交换
开发语言
夜珀23 分钟前
OpenTiny NEXT 从入门到精通·第 2 篇
开发语言·前端框架
Fcy64827 分钟前
算法基础详解(五)二分算法——二分查找与二分答案
算法·二分算法
郭涤生29 分钟前
原子操作的内存顺序
c++
ALex_zry42 分钟前
C++模板元编程实战技巧
网络·c++·windows