首页 > 代码库 > [leetcode]Plus One

[leetcode]Plus One

问题描述:

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