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

[leetcode]Plus One

时间:2014-10-28 17:49:25      阅读:147      评论: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.Vector;   //java


public class PlusOne {

	 public int[] plusOne(int[] digits) {
	        Vector<Integer> vec = new Vector<Integer>();
	        
	        int r = 1;
	        int tmp = 0;
	        int i = digits.length-1; 
	        while(i>=0 && r!=0){
	        	tmp = r + digits[i--];
	        	if(tmp >= 10){
	        		vec.add(tmp%10);
	        		r = 1;
	        	}
	        	else{
	        		vec.add(tmp);
	        		r = 0;
	        	}
	        }
	        
	        if(r==1){
	        	int[] result = new int[digits.length+1];
	        	result[0] = 1;
	        	return result;
	        }
	        else{
	        	int [] result = new int[digits.length];
	        	int pos = 0;
	        	for(i=0; i<digits.length-vec.size();){
	        		result[pos++] = digits[i++]; 
	        	}
	        	for(i = vec.size()-1; i>=0; i--)
	        		result[pos++] = vec.get(i);
	        	return result;
	        }
	}
}


[leetcode]Plus One

标签:算法

原文地址:http://blog.csdn.net/chenlei0630/article/details/40543129

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