258.整形每个组成数字相加 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?



  1. public int AddDigits(int num) {
  2. char[] nums = num.ToString().ToCharArray();
  3. if (num / 10 >= 1) {
  4. int sum = 0;
  5. foreach (char c in nums) {
  6. sum += (Convert.ToInt32(c) - 48);
  7. }
  8. return AddDigits(sum);
  9. } else {
  10. return num;
  11. }
  12. }





posted @ 2017-01-10 23:03  xiejunzhao  阅读(143)  评论(0编辑  收藏  举报