[Leetcode][数论]Add Digits
来源:互联网 发布:石油钻井数据与油价 编辑:程序博客网 时间:2024/04/30 11:06
题目描述:
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.
思路:
前提条件:给定一个数字,如果不同位上数字之和小于10返回,否则重复不同位上数字相加的过程
思维过程:对于需要重复进行的过程需要抽象为函数,输入是一个整数,输出是这个整数各个数位相加之和,便捷的做法是将整数转化为字符串,因为字符串底层是由char[]实现的,自动实现各个数位的分离。主程序只需要判断各个数位相加之和是否小于10即可
代码实现:
public class Solution { public int addDigits(int num) { int next = getNext(num); while(next >= 10){ next = getNext(next); } return next; } private int getNext(int num){ String s = String.valueOf(num); int sum = 0; for(char ch:s.toCharArray()){ sum += (ch - '0'); } return sum; }}
0 0
- [Leetcode][数论]Add Digits
- [leetcode][math] Add Digits
- [leetcode] Add Digits
- 【leetcode】Add Digits【java】
- Leetcode: Add Digits
- LeetCode Add Digits
- [LeetCode] Add Digits
- leetcode 258: Add Digits
- LeetCode题解:Add Digits
- leetcode: Add Digits
- 258Add Digits - LeetCode
- leetCode #258 Add Digits
- [LeetCode 258] Add Digits
- LeetCode: Add Digits
- LeetCode:Add Digits
- leetcode--add digits
- leetcode Add Digits
- leetcode--Add Digits
- 浅析人脸检测之Haar分类器方法:Haar特征、积分图、 AdaBoost 、级联
- cmd下演示SQLite
- 非阻塞式线程安全列表
- 好基友的博客,顶一下,备份一下
- UITableView的段落设置 — 段头段尾高度
- [Leetcode][数论]Add Digits
- 人机大战之AlphaGo的硬件配置和算法研究
- PHP进阶:取得当前的Unix时间戳
- 敏捷开发之Scrum扫盲篇
- 使用appium进行ios测试,启动inspector时遇到的问题(一)
- Span 介绍及使用(一)
- Java并发编程(二)——Thread.currentThread()研究
- 栈在java中的实现
- Span 介绍及使用(二)