題目要求:一個非負整數被表示爲一個數組,數組中每個元素表明該整數的一個位。數組的下標越小,表明的位數越高。如今對該數組作加一運算,請返回結果數組。git
/** * @author rale * * 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. */ public class PlusOne { public int[] plusOne(int[] digits) { //此處能夠直接將carry(進位)設置爲1,優化程序 //carry = 0 //digits[digits.length-1] += 1 ; int carry = 1; int temp = 0; for(int i=digits.length-1 ; i>=0 ; i--){ temp = digits[i] + carry; digits[i] = temp%10; carry = temp/10; } if(carry>0){ int[] result = new int[digits.length+1]; result[0] = 1; for(int j = 1 ; j<result.length ; j++){ result[j] = digits[j-1]; } return result; } return digits; } }
繼續優化
只有當須要進位的時候,加法才須要繼續下去,不然加法則能夠在當前位中止。
能夠在循環中添加判斷,若carry==0,則提早跳出循環面試
/** * @author rale * * 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. */ public class PlusOne { public int[] plusOne(int[] digits) { //此處能夠直接將carry(進位)設置爲1,優化程序 //carry = 0 //digits[digits.length-1] += 1 ; int carry = 1; int temp = 0; for(int i=digits.length-1 ; i>=0 ; i--){ temp = digits[i] + carry; digits[i] = temp%10; carry = temp/10; if(carry==0){ break } } if(carry>0){ int[] result = new int[digits.length+1]; result[0] = 1; for(int j = 1 ; j<result.length ; j++){ result[j] = digits[j-1]; } return result; } return digits; } }
再再再次優化
此處優化最高位進位的狀況
最高位出現進位,當且僅當其餘位都產生進位且爲0
優化後的代碼以下數組
/** * @author rale * * 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. */ public class PlusOne { public int[] plusOne(int[] digits) { int carry = 1; int temp = 0; for(int i=digits.length-1 ; i>=0 ; i--){ temp = digits[i] + carry; digits[i] = temp%10; carry = temp/10; } if(carry>0){ int[] result = new int[digits.length+1]; result[0] = 1; // 最高位進位的狀況只有一種,即其它位均進位且爲0,無需再循環一次 // for(int j = 1 ; j<result.length ; j++){ // result[j] = digits[j-1]; // } return result; } return digits; } }
想要了解更多開發技術,面試教程以及互聯網公司內推,歡迎關注個人微信公衆號!將會不按期的發放福利哦~微信