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. }





转载于:https://www.cnblogs.com/xiejunzhao/p/303ffe5f2ebd20b7b7ce22182f13f166.html

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐