首页 > 其他 > 详细

[leetcode] Plus One

时间:2015-02-05 11:23:38      阅读:256      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!