258.整数各位相加,最后得到仅一位的数字 Add Digits

Given an array of integers, every element appears twice except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?


有一个非负整数num,重复这样的操作:对该数字的各位数字求和,对这个和的各位数字再求和……直到最后得到一个仅1位的数字(即小于10的数字)。

例如:num=38,3+8=11,1+1=2。因为2小于10,因此返回2。

  1. /*
  2. Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
  3. For example:
  4. Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
  5. Follow up:
  6. Could you do it without any loop/recursion in O(1) runtime?
  7. */
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Linq;
  11. using System.Text;
  12. namespace Solution {
  13. public class Solution {
  14. public int AddDigits(int num) {
  15. char[] nums = num.ToString().ToCharArray();
  16. if (num / 10 >= 1) {
  17. int sum = 0;
  18. foreach (char c in nums) {
  19. sum += (Convert.ToInt32(c) - 48);
  20. }
  21. return AddDigits(sum);
  22. } else {
  23. return num;
  24. }
  25. }
  26. //one line solution
  27. public int AddDigits(int num) {
  28. return (num - 1) % 9 + 1;
  29. }
  30. }
  31. class Program {
  32. static void Main(string[] args) {
  33. var s = new Solution();
  34. var res = s.AddDigits(38);
  35. Console.WriteLine(res);
  36. }
  37. }
  38. }





原文地址:https://www.cnblogs.com/xiejunzhao/p/ade15e3ed79873020bfb75ca48808306.html