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 = 11
, 1 + 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 }
时间: 2024-11-10 01:10:01