zoukankan      html  css  js  c++  java
  • 20 Plus One

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

    The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.

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

    Example 1:

    Input: [1,2,3]
    Output: [1,2,4]
    Explanation: The array represents the integer 123.
    Example 2:

    Input: [4,3,2,1]
    Output: [4,3,2,2]
    Explanation: The array represents the integer 4321.

    一道简答难度的加法题目,关键是对进位的处理。

    class Solution {
    public:
        vector<int> plusOne(vector<int>& digits) {
           
            int len = digits.size();
            int c = 0;
            
            vector<int> ans = digits;
            
            for(int i=len-1;i>=0;i--)
            {
                
                if(i == len -1 ){
                    
                    ans[i] = (digits[i] + 1 + c)%10;
                    c = ( (digits[i] + 1) < 10 ) ? 0:1 ;
                    
                } 
                else{
                    
                    ans[i] = (digits[i] + c)%10;
                    c = ( (digits[i] + c) < 10 ) ? 0:1 ;
          
                } 
                
            }
            
         
            if(c==1) ans.insert(ans.begin(),1);
            
            return ans;
            
        }
    };
    
  • 相关阅读:
    Navicat远程连接服务器Mysql
    JSP与Servlet之间传值
    JSP获取绝对路径
    PIL的库学习
    科学计算与可视化
    预测球类比赛结果
    预测球类比赛结果
    汉诺塔问题
    有进度条圆周率计算
    turtle学习心得
  • 原文地址:https://www.cnblogs.com/xiaoyisun06/p/11386361.html
Copyright © 2011-2022 走看看