66. Plus One

Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.

You may assume the integer do not contain any leading zero, except the number 0 itself.

The digits are stored such that the most significant digit is at the head of the list.

 

给一个数组,这个数组代表一个整数,对这个整数+1

 

C++(3ms):

 1 class Solution {
 2 public:
 3     vector<int> plusOne(vector<int>& digits) {
 4         int len = digits.size() ;
 5         for(int i = len-1 ; i >= 0 ; i--){
 6             if (digits[i] == 9)
 7                 digits[i] = 0 ;
 8             else{
 9                 digits[i]++ ;
10                 return digits;
11             }
12         }
13         digits[0] = 1 ;
14         digits.push_back(0) ;
15         return digits ;
16     }
17 };

 

java(0ms):

 1 class Solution {
 2     public int[] plusOne(int[] digits) {
 3         for (int i = digits.length-1;  i >= 0 ; i--){
 4             if (digits[i] == 9){
 5                 digits[i] = 0 ;
 6             }else{
 7                 digits[i]++ ;
 8                 return digits ;
 9             }
10         }
11         int[] res = new int[digits.length+1] ;
12         res[0] = 1 ;
13         return res ;
14     }
15 }

 

posted @ 2017-09-28 09:31  __Meng  阅读(172)  评论(0编辑  收藏  举报