码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode No.258 Add Digits

时间:2015-10-26 16:55:15      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:

LeetCode  Algorithum

# title solution difficulty
258  Add Digits  java  easy
       

 

NO.258 (2015.10.26 16:09:00)

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 = 111 + 1 = 2. Since 2 has only one digit, return it.

给定一个非负整数num,反复添加所有位数字知道只剩下一位数。

比如:给定一个非负整数 num = 38,过程就像这样:3 + 8 = 11, 1 + 1 = 2,从两位一直到一位数,返回最后相加得到的这个数字。

 1 public class Solution {
 2     public int addDigits(int num) {
 3         int result = 0;//定义最终相加结果
 4         String number = num + "";
 5         if(num >= 10) {//如果大于10,则进行相加,否则直接返回
 6             result = getResult(number);
 7             while(result >= 10) {//返回结果如果大于等于10,则继续进行相加
 8                 result = getResult(result + "");
 9             }
10         } else {
11             return num;
12         }
13         return result;
14     }
15     
16     //循环遍历返回总数
17     public int getResult(String number) {
18         int result = 0;
19         for(int i = 0; i < number.length(); i++) {
20             result += Integer.parseInt(number.charAt(i) + "");
21         }
22         return result;
23     }
24 }

 

LeetCode No.258 Add Digits

标签:

原文地址:http://www.cnblogs.com/bbm7/p/4911566.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!