【LeetCode大法】Plus One
来源:互联网 发布:女子支付网络被刑拘 编辑:程序博客网 时间:2024/06/11 07:47
题意:
Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.
You may assume the integer do not contain any leading zero, except the number 0 itself.
The digits are stored such that the most significant digit is at the head of the list.
原题链接:https://leetcode.com/problems/plus-one/#/description
我知道你看不懂,给你翻译翻译:
就是给你一串非负非空整形数组,数组是由整数构成,每一位都存在数组里面,最高位存在最前面,例如 998,那这串数组就是{9,9,8},然后做加1操作,返回一串数组出来。还是{9,9,8},返回是{9,9,9},如果是{9,9},则返回的是{1,0,0}
思路:无非就是从数组尾加上来,在这个过程需要一个记录因子,记录是否需要进位加1,然后把值存在一个新数组,再最后for完之后看看这个记录因子是1还是0,定返回数组的长度,1把这个返回因子加上去,0不加,然后把新数组加上去。
完美。
No BB
Show Me Code!
代码:
public static int[] plusOne(int[] digits) {int length = digits.length;int[] newDigits = new int[length];//記錄是否進位int recordDigit = 1;for(int i = length-1; i >= 0; i--){if(digits[i] == 9 && recordDigit == 1){newDigits[i] = 0;recordDigit = 1;} else {newDigits[i] = digits[i] + recordDigit;recordDigit = 0;}}int[] resultDigits = new int[length + recordDigit];if(recordDigit == 1){resultDigits[0] = 1;}for(int i = recordDigit; i < length; i++){resultDigits[i] = newDigits[i-recordDigit];}return resultDigits;}
呵呵,解决!
之后有时间再看看有没有什么其他更快的解法。
阅读全文
1 0
- 【LeetCode大法】Plus One
- LeetCode: Plus One
- LeetCode Plus One
- [Leetcode] Plus One
- LeetCode: Plus One
- leetcode 33: Plus One
- [LeetCode] Plus One
- [leetCode] Plus One
- 【leetcode】Plus One
- [LeetCode]Plus One
- [leetcode]Plus One
- LeetCode-Plus One
- [leetcode] plus one
- LeetCode - Plus One
- [LeetCode] Plus one
- LeetCode:Plus One
- leetcode之Plus One
- leetcode plus one
- Android多媒体开发-- android中OpenMax的实现整体框架
- error C2143: 语法错误 : 缺少“;”(在“*”的前面) error C4430: 缺少类型说明符
- Android中对文件保存、读取和删除操作的实现
- JS--第六天
- Java 集合系列11之 Hashtable源码解析
- 【LeetCode大法】Plus One
- CodeForces 21 D.Traveling Graph(状压DP+Floyd)
- 如何在Linux下搭建流媒体服务器系统
- 解密浏览器缓存机制
- destoon代码从头捋一遍
- mysql:1130-host ... is not allowed to connect to this MySql server 开放mysql远程连接 不使用localhost
- Android BLE学习笔记
- Apps using background location services must provide a reason that clarifies the purpose of the use
- unordered_map