标签:
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.
思路:
思路很简单,遍历一遍,记录数值即可
我的代码:
public class Solution { public int[] plusOne(int[] digits) { if(digits == null || digits.length == 0) return digits; int plus = 1; for(int i = digits.length - 1; i >= 0; i--) { int sum = digits[i] + plus; if(sum == 10) { digits[i] = 0; plus = 1; } else { digits[i] = sum; plus = 0; } } if(plus == 0) return digits; else { int[] rst = new int[digits.length + 1]; rst[0] = plus; for(int i = 1; i < rst.length; i++) { rst[i] = digits[i-1]; } return rst; } } }
他人代码:
public class Solution { public int[] plusOne(int[] digits) { int carries = 1; for(int i = digits.length-1; i>=0 && carries > 0; i--){ // fast break when carries equals zero int sum = digits[i] + carries; digits[i] = sum % 10; carries = sum / 10; } if(carries == 0) return digits; int[] rst = new int[digits.length+1]; rst[0] = 1; for(int i=1; i< rst.length; i++){ rst[i] = digits[i-1]; } return rst; } }
学习之处:
标签:
原文地址:http://www.cnblogs.com/sunshisonghit/p/4322164.html