Leetcode 258. Add Digits JAVA语言

本文介绍了一个简单的算法问题:给定一个非负整数,通过反复累加其各位数字直到结果仅剩一位数,并提供了一种使用循环和递归相结合的方法来解决该问题。此外,还探讨了不使用循环和递归的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1
2
3
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
For example:
Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.

题意:给一个非负整数,求其各位数的和只至最后是个位数。

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Solution {
    public int addDigits(int num) {
        ////循环和递归解决~
        int sum=0;
        if(num/10==0)return num;
        while(num!=0){
            sum=sum+num%10;
            num=num/10;
        }
        // System.out.println(sum);
        return addDigits(sum);
    }
}

PS:额,直接循环加递归解决。。。。


进阶:不使用循环和递归。



本文转自 努力的C 51CTO博客,原文链接:http://blog.51cto.com/fulin0532/1890563
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值