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;
    }
};
相关推荐
笑鸿的学习笔记5 分钟前
qt-C++语法笔记之Stretch与Spacer的关系分析
c++·笔记·qt
留不住丨晚霞9 分钟前
说说SpringBoot常用的注解?
java·开发语言
hardStudy_h19 分钟前
C++——内联函数与Lambda表达式
开发语言·jvm·c++
vortex530 分钟前
算法设计与分析 知识总结
算法
艾莉丝努力练剑1 小时前
【C语言】学习过程教训与经验杂谈:思想准备、知识回顾(三)
c语言·开发语言·数据结构·学习·算法
ZZZS05161 小时前
stack栈练习
c++·笔记·学习·算法·动态规划
黑听人1 小时前
【力扣 困难 C】115. 不同的子序列
c语言·leetcode
位东风1 小时前
【c++学习记录】状态模式,实现一个登陆功能
c++·学习·状态模式
hans汉斯1 小时前
【人工智能与机器人研究】基于力传感器坐标系预标定的重力补偿算法
人工智能·算法·机器人·信号处理·深度神经网络
witton2 小时前
Go语言网络游戏服务器模块化编程
服务器·开发语言·游戏·golang·origin·模块化·耦合