258Add Digits

来源:互联网 发布:淘宝闺蜜投诉平台 编辑:程序博客网 时间:2024/05/29 17:36

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.

https://en.wikipedia.org/wiki/Digital_root

Solution1 Straightforward way

public class Solution {    public int addDigits(int num) {        while(num>=10){              num = (num/10)+num%10;          }          return num;      }}
简单的问题总是会有简单的方法,如果你没有找到,也只是说明你没有找到而已。一个数的数字根(digit root)就是将该数的所有数字加起来,循环往复,直到只有一位数字为止。譬如 345, 3+4+5=12,1+2=3,那么 345 的数字根就是 3。代码可以如此简单,只要你发现了 root(10x+y) = root(x+y) 实际上 root(x) = x % 9 这个真相就好了。 也就是一个数 n 的数字根就是 n % 9 !不过因为数 n 除了 0 时数字根是 0 之外,其他时候是取值 1 - 9,所以 n % 9 如果为 0 的时候数字根是 9 !用一个小技巧处理便是: (n-1) % 9 + 1 !
int addDigits(int num) {    return (num-1)%9+1;}


0 0
原创粉丝点击