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;
    }
};
相关推荐
寻星探路13 小时前
【深度长文】万字攻克网络原理:从 HTTP 报文解构到 HTTPS 终极加密逻辑
java·开发语言·网络·python·http·ai·https
lly20240614 小时前
Bootstrap 警告框
开发语言
2601_9491465315 小时前
C语言语音通知接口接入教程:如何使用C语言直接调用语音预警API
c语言·开发语言
你撅嘴真丑15 小时前
第九章-数字三角形
算法
曹牧15 小时前
Spring Boot:如何测试Java Controller中的POST请求?
java·开发语言
在路上看风景15 小时前
19. 成员初始化列表和初始化对象
c++
KYGALYX15 小时前
服务异步通信
开发语言·后端·微服务·ruby
uesowys15 小时前
Apache Spark算法开发指导-One-vs-Rest classifier
人工智能·算法·spark
zmzb010315 小时前
C++课后习题训练记录Day98
开发语言·c++
ValhallaCoder15 小时前
hot100-二叉树I
数据结构·python·算法·二叉树