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;
            
        }
    };
    
  • 相关阅读:
    c# 代码控制文件夹权限时,只显示特殊权限的问题
    C#使用SQLite数据库遇到的问题(二)
    GC工作原理
    Thread
    -static
    String 练习题
    更进ATM
    继承 示例
    数组
    求奇偶数
  • 原文地址:https://www.cnblogs.com/xiaoyisun06/p/11386361.html
Copyright © 2011-2022 走看看