码迷,mamicode.com
首页 > 编程语言 > 详细

Java [Leetcode 66]Plus One

时间:2016-01-22 00:04:33      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:

题目描述:

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.

解题思路:

设置进位,如果数组不够的话记得重新开辟空间。

代码如下:

public class Solution {
    public int[] plusOne(int[] digits) {
    	int carry = 0;
    	if(digits == null || digits.length == 0)
    		return null;
    	else
    		digits[digits.length - 1] += 1;
        for(int i = digits.length - 1; i >= 0; i--){
        	int cur = carry + digits[i];
        	carry = cur / 10;
        	digits[i] = cur % 10;
        }
        if(carry != 0){
        	int[] newDigits = new int[digits.length + 1];
        	System.arraycopy(digits, 0, newDigits, 1, digits.length);
        	newDigits[0] = carry;
        	return newDigits;
        } else {
        	return digits;
        }
    }
}

  

Java [Leetcode 66]Plus One

标签:

原文地址:http://www.cnblogs.com/zihaowang/p/5149838.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!