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;
    }
};
相关推荐
摇滚侠20 分钟前
Java 中如何表示负数,有符号和无符号的区别,补码的计算规则,char byte short int long 的范围
java·开发语言
OPEN-F35 分钟前
ROS2系列教程:上位机建图与导航(原理综合)
算法·机器人
weixin_3077791336 分钟前
C++代码实现MATLAB中的fitrtree函数功能
开发语言·c++·算法·matlab
AI wins40 分钟前
c++新增頭文件
c++
Shadow(⊙o⊙)1 小时前
仿muduo实现高并发服务器——事件就绪管理Channel.hpp
服务器·c++
爱读书的小胖1 小时前
Codewars:Rot13(C)解题分析
c语言·开发语言
tomwang03221 小时前
路径优化建模、优化算法分类及工程化小结
算法·数学建模·分类
小羊没烦恼!1 小时前
Ajax与JSON的一些总结
android·java·前端·数据库·mysql·算法·okhttp
鸽鸽程序猿1 小时前
【项目】【在线判题系统】b端题目增删改
开发语言·python
by209991 小时前
哈希表——快速找到数据:冲突、删除与扩容的实现
数据结构·c++·哈希算法·散列表