258. Add Digits

来源:互联网 发布:数据统计问题有哪些 编辑:程序博客网 时间:2024/05/28 15:06

258. Add Digits

DescriptionHintsSubmissionsDiscussSolution
DiscussPick One

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?

Credits:

Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.


题意:

给定一个整数,求其各位之和,直到只剩下一位数


算法思路:

循环相加直到小于10即可


代码:

package easy;/*@author wchstrife@version 2017年7月22日下午11:03:12*/public class AddDigits {public int addDigits(int num) {while(num >9){num = num/10 + num%10;}return num;}}


原创粉丝点击