码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode] Plus One

时间:2015-02-05 11:26:14      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:

Plus One

 Total Accepted: 34829 Total Submissions: 111864My Submissions

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.


package com.wyt.leetcodeOJ;

import java.util.Arrays;

public class PlusOne {

	public static void main(String[] args) {
		int[] digits = {9,9};
		System.out.println(Arrays.toString(plusOne(digits)));
	}
	
	public static int[] plusOne(int[] digits) {
		if(digits == null || digits.length == 0) {
			return digits;
		}
		
		int len = digits.length;
		if(digits[len - 1] < 9) {
			digits[len - 1] ++;
			return digits;
		}
		
		if(len == 1) {
			digits = new int[2];
			digits[0] = 1;
			digits[1] = 0;
			return digits;
		} else {
			int k = len;
			digits[len - 1] = 0;
			for (int i = len - 2; i >= 0; i--) {
				if(digits[i] < 9) {
					digits[i]++;
					break;
				} else {
					digits[i] = 0;
				}
				k--;
			}
			if(k==1) {
				digits = new int[len+1];
				digits[0] = 1;
			}
			return digits;
		}
    }
	
}


[leetcode] Plus One

标签:

原文地址:http://blog.csdn.net/intmain_rocking/article/details/43524273

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