美文网首页
2019-01-29 Day 24

2019-01-29 Day 24

作者: 骚得过火 | 来源:发表于2019-01-29 20:45 被阅读0次
  1. 加1

给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。

最高位数字存放在数组的首位, 数组中每个元素只存储一个数字。

你可以假设除了整数 0 之外,这个整数不会以零开头。

示例 1:

输入: [1,2,3]
输出: [1,2,4]
解释: 输入数组表示数字 123。
示例 2:

输入: [4,3,2,1]
输出: [4,3,2,2]
解释: 输入数组表示数字 4321。

class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
    
        int flag = 1 ;
        int index  = digits.size()-1;
        
        vector<int> res;
        
        while( index >= 0)
        {        
              if( digits[index] +1 == 10 )
               { 
                  
                   res.push_back( 0 );
                   if(index == 0)
                   res.push_back( 1 );
                
               }
               else
               {
                   res.push_back( digits[index] +1 ) ;
                   break;
               }
               index -- ;
        }
        index --;
        while( index >=0)
        {
            
            res.push_back( digits[index]);
            index --;
        }
        
        int end = res.size() -1;
        int head = 0;
        while(end >head)
        {
           int temp = res[head];
           res[head] = res[end];
           res[end] = temp;
            end --;head++;
            
        }
        
        return res ;
        
        
    }
};

相关文章

网友评论

      本文标题:2019-01-29 Day 24

      本文链接:https://www.haomeiwen.com/subject/nvrfsqtx.html