AddDigitsTotal - 把数字中单个数相加

给定一个int数字,把数字中的单个数相加起来;得到的结果如果不是个位数,继续相加

如给定 19,执行1+9 = 10 --> 1 + 0 = 1  返回1

给定22,返回4

思路很简单,把各个位置上的数字取出来相加;结果如果大于9,继续执行相加

Java代码实现:

 1 public class AddDigitsTotal {
 2     public static int addOnce(int n) {
 3         int result = 0;
 4         while (n != 0) {
 5             result += n%10;
 6             n = n/10;
 7         }
 8         return result;
 9     }
10 
11     public static int addDigits(int num) {
12         int res = 0;
13         res = addOnce(num);
14         while (res > 9) {
15             res = addOnce(res);
16         }
17         return res;
18     }
19     public static void main(String args[]){
20         for (int i = 900; i < 919; i++) {
21             System.out.print((i) + "\t");
22         }
23         System.out.println();
24         for (int i = 900; i < 919; i++) {
25             System.out.print(addDigits(i) + "\t");
26         }
27         for (int i = 0; i < 10000; i++) {
28             if (addDigits(i) >= 10) {
29                 System.out.print("ERROR");
30             }         
31         }
32     }
33 }

 输出:

900	901	902	903	904	905	906	907	908	909	910	911	912	913	914	915	916	917	918	
9	1	2	3	4	5	6	7	8	9	1	2	3	4	5	6	7	8	9	

  

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值