leetcode题库之258
来源:互联网 发布:apache tomcat modjk 编辑:程序博客网 时间:2024/04/30 23:56
258/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.
中文翻译:给定一个正数,将其所有位数上的数字进行相加得到一个新的数。不断反复,直到得到的数是一位数的。
解题思路:
1.先要保存好num各位上的数字
2.将保持好的数字进行相加得到新的num
3.反复操作,直到num满足只有一位数的要求
一开始是先想到要用到数组来对各位数的数进行存储,程序写好后想对代码进行优化,想了一下发现其实可以不需要用到数组,只用一个辅助变量其实就能实现。改完后百度了一下,发现还有一个更简单的方法,其实该题是有规律的。。。
最开始的程序算法:
int addDigits(int num) { int i=0,j=0; int tem = num; int a[100]; while((num/10)>0) //遍历num各位上的数字,并存放在数组a中 { while((tem/10)>0) { a[i] = tem%10; tem=tem/10; i++; } for(j=0;j<i;j++) //将存储好的数字分别相加得到新的num { tem+=a[j]; } i=0; //数组下标置0,重复对num各位数字的遍历 num=tem; } return num;}
优化了下代码:
int addDigits(int num) { int tem=0; while((num/10)>0) { while((num/10)>0) //遍历num每位的数字 { tem+= num%10; //得出num各位上的数字后直接相加 num=num/10; } num+=tem; tem=0; } return num;}
根据规律来实现:
int addDigits(int num) { return (num-1)%9+1;}
0 0
- leetcode题库之258
- leetcode题库之257
- leetcode题库之242
- leetcode题库之241
- LeetCode题库之Number of 1 Bits
- LeetCode题库——TwoSum
- LeetCode题库——AddTwoNumbers
- LeetCode题库——LongestSubstringWithoutRepeatingCharacters
- NOI题库之二分 派
- github上的leetcode题库App开发
- 题库
- 题库
- 题库
- 题库
- 题库
- 题库
- 题库
- 题库
- python入门教程
- Cocoadpods的使用
- native c++/qt中如何调用c#dll
- MinGW+Notepad++编译运行 C++代码
- Win7远程连接常出现的密码错误
- leetcode题库之258
- Leetcode163: Word Ladder
- TPM模拟器安装及使用说明
- ThreadPoolExecuter 原理机制
- 引用与指针区别
- Cocos2dx 中文乱码的解决方法
- 动态规划:求最大子段和
- [原]8小时外实践系列之四——从零开始建立一个个人网站
- 数据结构 — 图 之 广度优先遍历