[LeetCode]258. Add Digits

来源:互联网 发布:新开淘宝店如何刷信誉 编辑:程序博客网 时间:2024/06/14 14:50

题目描述: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 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.

解题思路:循环判断条件temp/10>0,将当前的数字拆解相加。

public int addDigits(int num){        //当num为个位数时,直接返回        if(num/10<=0)return num;        int temp = num;        while(temp/10>0){            //digit不只一个            int sum = 0;            while(temp>0){                sum+=temp%10;                temp=temp/10;            }            temp = sum;        }        return temp;    }
原创粉丝点击