首页 > 其他 > 详细

LeetCode | Plus One

时间:2014-03-08 09:17:50      阅读:416      评论: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.

分析

这题也没啥特别技巧吧,别用除法、取余的操作就好

代码

import java.util.ArrayList;

public class PlusOne {
	public int[] plusOne(int[] digits) {
		if (digits == null || digits.length == 0) {
			return digits;
		}
		ArrayList<Integer> list = new ArrayList<Integer>();
		int carry = 1;
		for (int i = digits.length - 1; i >= 0; --i) {
			if (carry == 1 && digits[i] == 9) {
				list.add(0);
			} else {
				list.add(digits[i] + carry);
				carry = 0;
			}
		}
		if (carry == 1) {
			list.add(1);
		}
		int N = list.size();
		int[] results = new int[N];
		for (int i = 0; i < N; ++i) {
			results[i] = list.get(N - 1 - i);
		}
		return results;
	}
}


LeetCode | Plus One,布布扣,bubuko.com

LeetCode | Plus One

原文:http://blog.csdn.net/perfect8886/article/details/20741509

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!