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;
    }
};
相关推荐
Struggle_97553 分钟前
算法知识-从递归入手三维动态规划
算法·动态规划
xiaoshuaishuai87 分钟前
C# 实现百度搜索算法逆向
开发语言·windows·c#·dubbo
yuan199979 分钟前
使用模糊逻辑算法进行路径规划(MATLAB实现)
开发语言·算法·matlab
不才小强12 分钟前
线性表详解:顺序与链式存储
数据结构·算法
CoovallyAIHub12 分钟前
上交+阿里 | Interactive ASR:Agent框架做语音识别交互纠错,1轮交互语义错误率降57%
算法·架构·github
Aaron158823 分钟前
8通道测向系统演示科研套件
人工智能·算法·fpga开发·硬件工程·信息与通信·信号处理·基带工程
计算机安禾28 分钟前
【数据结构与算法】第42篇:并查集(Disjoint Set Union)
c语言·数据结构·c++·算法·链表·排序算法·深度优先
吃着火锅x唱着歌30 分钟前
LeetCode 150.逆波兰表达式求值
linux·算法·leetcode
蒸汽求职34 分钟前
北美求职身份过渡:Day 1 CPT 的合规红线与安全入职指南
开发语言·人工智能·安全·pdf·github·开源协议
YuanDaima20481 小时前
二分查找基础原理与题目说明
开发语言·数据结构·人工智能·笔记·python·算法