您的位置:首页 > 其它

leetcode--Plus One

2017-08-08 09:38 357 查看
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来表示进位。

[java] view
plain copy

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;  

    }  



原文链接http://blog.csdn.net/crazy__chen/article/details/46008945
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: