【Leetcode】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?

---------------------------------------------------SOLUTION BELOW---------------------------------------------------

The idea is simple. Write a loop to record the length of the number, which means how many digits. And another loop for counting the sum of current number. It shocked me because it took me more than 10 minutes to write about it!!! I have been away from Leetcode really long time. I really should spend more time on algorithms and data structure. Besides, I will also start to write what I learnt in J2EE in the past year and keep updating in this blog. My current project in UfT is also attractive and I would move it here if possible. It's a shame here is not a SVN, pity.

First Solution:

package testAndfun;

public class addDigit {
	public static void main(String args[]){
		int num = 12;
		addDigit ad = new addDigit();
//		System.out.println(cal(209874));
		System.out.println(ad.addDigits(num));
	}
	public int addDigits(int num) {
		while((num+"").length()!=1){
			int tmp = 0;
			while(num!=0){
			tmp += num % 10;
			num = num / 10;
//			System.out.println(num);
			}
			num = tmp;
			
		}
		return num;
    }
	
}
However, if you could observe the pattern of the answer. Let me show you:

-------------------------------------

| when input is 0 the answer is 0 |

| when input is 1 the answer is 1 |

| when input is 2 the answer is 2 |

| when input is 3 the answer is 3 |

| when input is 4 the answer is 4 |

| when input is 5 the answer is 5 |

| when input is 6 the answer is 6 |

| when input is 7 the answer is 7 |

| when input is 8 the answer is 8 |

| when input is 9 the answer is 9 |

| when input is 10 the answer is 1 |

| when input is 11 the answer is 2 |

| when input is 12 the answer is 3 |

| when input is 13 the answer is 4 |

| when input is 14 the answer is 5 |

| when input is 15 the answer is 6 |

| when input is 16 the answer is 7 |

| when input is 17 the answer is 8 |

| when input is 18 the answer is 9 |

| when input is 19 the answer is 1 |

| when input is 20 the answer is 2 |

-------------------------------------

Do you see? The pattern is bloody easy. I will just write it down. This time, Python.

class Solution:
    def addDigits(self, num):
        if num == 0:
            return 0
        return (num - 1) % 9 + 1


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值