Leetcode 66. Plus One

来源:互联网 发布:服装数据分析公式 编辑:程序博客网 时间:2024/06/09 21:51
//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 Main {public static void main(String[] args){System.out.println(plusOne(new int[]{1,9}));}public static int[] plusOne(int[] digits) {int carry = 1;for(int i = digits.length-1;i>=0;i--){int val = digits[i]+1;carry = val/10;//是否有进位digits[i] = val%10;//当前数字加一后是多少if(carry == 0){//如果没有进位就直接返回return digits;}}if(carry == 1){//如果增加了以为就新建数组使最高位为1int[] result1 = new int[digits.length+1];result1[0] = 1;return result1;}else{return digits;//否则返回digits}}}

原创粉丝点击