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;
    }
};
相关推荐
综合简报8 分钟前
黑五海外发稿投给谁?三类海外媒体发稿渠道的分工
开发语言·php·媒体
·present·14 分钟前
CSAPP(lecture 3)
c++
大风起兮云飞扬丶23 分钟前
Java——线程池
java·开发语言
别动我齐刘海39 分钟前
机器人 C++ / 系统联调补强2——异常处理、Protobuf
linux·c++·人工智能·学习·算法·机器学习·机器人
我命由我123451 小时前
Python 开发 - Python 虚拟环境
运维·开发语言·后端·python·http·https·java-ee
c#上位机1 小时前
C#上位机项目实战——exe项目调试更改dll中源代码
开发语言·c#
basketball6161 小时前
C++ 中字符串与常见类型的转换总结
开发语言·c++
梦影_1 小时前
MySQL进阶教程(一)—— 储存过程与触发器(上)
开发语言·数据库·后端·sql·mysql·中间件
fish_zzzz1 小时前
笔记-论数据结构1
数据结构
云和数据.ChenGuang1 小时前
LLM大模型对接本地Ollama部署模型
开发语言·人工智能·python·langchain