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.

给一个非负数,用一个数组来表示,数组每一项都是非负数的一位,再给这个数字加一。

非负数的那些位(个位十位百位等),高位在数位列表的前面,

123:    a[0] = 1 ;a[1] = 2; a[2] = 3;

123:【1】->【2】->【3】->null

 

represent as 把…描绘成:

e.g.  Conversely, some applications represent data as a matrix of many small contiguous pieces of data.

与之相反, 有些程序把数据表示为由许多连续的小片数据组成的矩阵.

 

digit

n.  位数;位;

数字 (从 0 到 9 的任何一个)digit is a written symbol for any of the ten numbers from 0 to 9.
e.g.   Her telephone number differs from mine by one digit.她的电话号码和我的只差一个数字。

 

public class MyPlusOne {
    public int[] plusOne(int[] digits) {
        boolean outFromPlus1 = false;
        ArrayList <Integer> digitsArray = new ArrayList<Integer>();

        for (int j = 0; j <= digits.length - 1; j++){  //stored in a  arraylist
            digitsArray.add(digits[j]);
        }

        int i;

        for ( i = digitsArray.size() - 1; i >= 0; i--) {   
            if (digitsArray.get(i) == 9){   //last digit is 9 so got to carry and loop
                digitsArray.set(i, 0);
            }
            else{
                digitsArray.set(i,digitsArray.get(i)+1);//last digit plus one and break 
                outFromPlus1 = true;
                break;
            }
        }
        if(-1 == i && !outFromPlus1) {  // not enough digits so add one from head
            digitsArray.add(0, 1);
        }

        int digitsPlusOne[] = toIntArray(digitsArray);
        return digitsPlusOne;
    }

    private int[] toIntArray(ArrayList<Integer> integerList) {//convert arraylist to int[]
        int[] intArray = new int[integerList.size()];
        for (int i = 0; i < integerList.size(); i++) {
            intArray[i] = integerList.get(i);
        }
        return intArray;
    }
}
Tagged on: ,

发表评论

电子邮件地址不会被公开。 必填项已用*标注

您可以使用这些HTML标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>