首页 > 代码库 > leetcode--Plus One
leetcode--Plus One
Given a non-negative number represented as an array of digits, plus one to the number.
The digits are stored such that the most significant digit is at the head of the list.
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | public class Solution { /**very fundamental problem.<br> * @author Averill Zheng * @version 2014-06-05 * @since JDK 1.7 */ public int [] plusOne( int [] digits) { int length = digits.length; int [] result = null ; if (length > 0 ){ int [] temp = new int [length + 1 ]; int carry = 1 ; for ( int i = length - 1 ; i > - 1 ; --i){ int sum = digits[i] + carry; carry = sum / 10 ; temp[i + 1 ] = sum % 10 ; } if (carry != 0 ) temp[ 0 ] = 1 ; if (temp[ 0 ] != 0 ) result = temp; else { result = new int [length]; for ( int i = 1 ; i < length + 1 ; ++i) result[i - 1 ] = temp[i]; } } return result; } } |
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。