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;
    }
};
相关推荐
马优晨2 分钟前
Java中的dto是什么
java·开发语言·java中的dto是什么·java的dto是什么·dto在java中是什么
七牛云行业应用4 分钟前
Muse Spark Open 发布:Meta 称其为美国最强开放权重模型,816B 参数如何落地
算法
itmigrate14 分钟前
PHP 导出大 CSV 时内存溢出的一次排查
android·开发语言·php
esop轻Mes看板亮灯分拣ESD静电安22 分钟前
产线“最后一米”的破局密码:ESOP与MES的区别与深度协同
算法
动词ing23 分钟前
[题目练习】三数之和
数据结构
陈天伟教授30 分钟前
《数据处理和标注技术》课程能力图谱
人工智能·算法
LMT_Lanmantech33 分钟前
HyperWorks许可:almutil显示Unit满了,数据到底准不准?
运维·服务器·算法
YSL07012434 分钟前
一文通关-----栈和队列
开发语言·数据结构
禁默44 分钟前
论文解读与思考:基于场所地图的标识感知机器人探索方法及工程参考的价值
人工智能·深度学习·算法·机器人
维克兜率天44 分钟前
【维克】统计套利建模:从因子到信号的完整流程
android·开发语言·python·算法·kotlin