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;
    }
};
相关推荐
郑州光合科技余经理1 小时前
代驾系统架构拆解:订单链路、权限组织与私有化源码交付
开发语言·后端·算法·架构·系统架构·uni-app·php
To_OC3 小时前
LC 35 搜索插入位置:二分查找谁都会,边界条件谁写谁懵
javascript·算法·leetcode
码哥DFS4 小时前
二叉树的直径
开发语言·javascript·算法
paopaokaka_luck4 小时前
基于springboot3+vue3的企业考勤管理系统(部门树递归、Echarts图形化分析)
开发语言·spring boot·学习·echarts·mybatis·需求分析·代码规范
梦雨生生6 小时前
java开发工具(学习第一天)
java·开发语言·学习
营养充电站7 小时前
KMP全栈开发:从Android到AI Agent的技术演进与实践
人工智能·算法·docker·jupyter
啊啊啊啊啊!!!!7 小时前
【c++】stack和queue的接口使用以及底层实现
开发语言·c++
技术小黑7 小时前
RNN算法实战系列05 | 天气预测
人工智能·rnn·算法
松仔log8 小时前
Java中级——组合和继承
android·java·开发语言