[leetcode]--258. Add Digits

叁歲伎倆 2022-07-11 15:57 300阅读 0赞

Question 258:

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

中文解释: 对于一个非负的整数n, 把其每位数的数字相加求和,直到其和小于10.

For example:

Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.

算法这里提供两种思路:

1)不断遍历求和直到小于10

这是一种比较直观的想法,只需要不断的求和就行了,下面给出代码:

  1. /** * 这个是最普通的算法,不停循环求出每位的和. * @By 娄宇庭 * @param num * @return */
  2. public static int addDigits(int num) {
  3. if(num<10)
  4. return num;
  5. int result = num;
  6. while (result>=10){
  7. int temp = 0;
  8. //将待求的多位数先转换成字符串再转换成字符数组;
  9. char[] numStrs = new Integer(result).toString().toCharArray();
  10. //遍历字符数组,获取每个字符数组代表的数,然后相加
  11. for(int i=0; i<numStrs.length; i++){
  12. temp += Integer.valueOf(String.valueOf(numStrs[i]));
  13. }
  14. result = temp;
  15. }
  16. return result;
  17. }

2)利用取余的特性求解:

example: 比如438
438 == 40*10 + 3*10 +8
4+3+8 == 4*(10%9)(10%9) + 3(10%9) + 8%9=15

再比如15:
15 == 1*10 +5
1+5 == 1*(10%9)+5%9 =6

得出规律: ab%9%9%9 == ab%9;

参考思路:
https://discuss.leetcode.com/topic/21588/1-line-java-solution

下面给出实现代码:

  1. public static int addDigits_reference(int num) {
  2. return num==0?0:(num%9==0?9: num%9);
  3. }

3. 测试:

  1. //测试用例
  2. public static void main(String[] args) {
  3. LogUtil.log_debug(""+addDigits_reference(38));
  4. }

运行结果:

  1. 2017-02-03 23:49:062

发表评论

表情:
评论列表 (有 0 条评论,300人围观)

还没有评论,来说两句吧...

相关阅读