题目要求:一个非负整数被表示为一个数组,数组中每个元素表明该整数的一个位。数组的下标越小,表明的位数越高。如今对该数组作加一运算,请返回结果数组。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; } }
想要了解更多开发技术,面试教程以及互联网公司内推,欢迎关注个人微信公众号!将会不按期的发放福利哦~微信