leetcode--Plus One

来源:互联网 发布:mac怎么查看激活时间 编辑:程序博客网 时间:2024/04/27 14:21

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.


题意:给定一个数组,元素都是非负数,整个数组用于表示一个整数。现在这个整数加1,求加1后的数组。

分类:数组,数学


解法1:从后往前加,注意保留flag来表示进位。

public class Solution {    public int[] plusOne(int[] digits) {        int len = digits.length;        int[] res = new int[len+1];        int flag = 1;        for(int i=len-1;i>=0;i--){            int t = digits[i]+flag;            flag = t/10;            digits[i] = t%10;            res[i] = t%10;        }        if(flag==1){            res[0] = 1;            return res;        }        return digits;    }}

0 0
原创粉丝点击