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

【Leetcode】Add Digits

时间:2016-06-12 02:43:27      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:

题目链接:https://leetcode.com/problems/add-digits/

题目:

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.

Follow up:
Could you do it without any loop/recursion in O(1) runtime?

Hint:

  1. A naive implementation of the above process is trivial. Could you come up with other methods?
  2. What are all the possible results?
  3. How do they occur, periodically or randomly?
  4. You may find this Wikipedia article useful.
思路:
1、暴力
2、举例说明一下。假设输入的数字是一个5位数字num,则num的各位分别为a、b、c、d、e。有如下关系:num = a * 10000 + b * 1000 + c * 100 + d * 10 + e 。即:num = (a + b + c + d + e) + (a * 9999 + b * 999 + c * 99 + d * 9) , a * 9999 + b * 999 + c * 99 + d * 9 一定可以被9整除,将num的每一位反复相加的结果即和将num模9的结果是一样的。

算法1:
[java] view plain copy
 技术分享技术分享
  1.   public int addDigits(int num) {  
  2.         while (num / 10 != 0) {  
  3.     char[] nums = Integer.toString(num).toCharArray();  
  4.     num = 0;  
  5.     for (int i = 0; i < nums.length; i++) {  
  6.         num +=  Integer.parseInt(String.valueOf(nums[i]));   
  7.     }  
  8. }  
  9. return num;  
  10.  }  

【Leetcode】Add Digits

标签:

原文地址:http://blog.csdn.net/yeqiuzs/article/details/51615486

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