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;
    }
};
相关推荐
从零开始学习人工智能7 小时前
国产阿特拉斯无人机蜂群核心算法(一)
算法·无人机
golang学习记7 小时前
Go 实时批处理:让数据库少挨点打 [特殊字符]
开发语言·数据库·golang
神の愛7 小时前
java的Aop
java·开发语言
励志的小陈7 小时前
双指针算法--移除元素、删除有序数组中的重复项、合并两个有序数组
算法
左左右右左右摇晃7 小时前
ConcurrentHashMap ——put + get
java·开发语言·笔记
今夕资源网8 小时前
零基础 Python 环境搭建工具 一键安装 Python 环境自动配置 升级 pip、setuptools、wheel
开发语言·python·pip·环境变量·python环境变量·python自动安装
Summer_Uncle8 小时前
【QT学习】Qt界面布局的生命周期和加载时机
c++·qt
小CC吃豆子8 小时前
C++ 继承
开发语言·c++
Derrick__18 小时前
Scrapling 爬取豆瓣电影Top250
开发语言·python·网络爬虫·豆瓣·scrapling
serve the people8 小时前
ACME 协议流程与AllinSSL 的关系(一)
开发语言