LeetCode : 258. Add Digits

来源:互联网 发布:深证指数数据 编辑:程序博客网 时间:2024/05/22 00:22

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.

实现代码如下:

public int addDigits(int num) {         int gewei;        int shiwei;        int hehge;        int shishi;        hehge = num%10;        shishi = num/10;        int ans=0;        int tmp;        tmp = num;        if(num <10) {            return num;        }        if(shishi*10 == num) {//            System.out.println("asd");            return shishi;        }else {            while (tmp !=0) {                gewei = num%10;                shiwei = num/10;                ans = gewei + shiwei;                num = ans;                tmp = num/10;                            }            return ans;        }      }


0 0