zoukankan      html  css  js  c++  java
  • 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.

    题意:一个非负整数按位存储于一个int数组中,排列顺序为:最高位在array[0] ,最低位在[n-1],例如:18,存储为:array[0]=1; array[1]=8;

    思路:可以从数组的最后一位开始加1,注意需要考虑进位,如果到[0]位之后仍然有进位存在,则需要在数组起始处新开一个位来存储。

    分析:从低位到高位,只有连续遇到9的情况最高位才能加1进位。所以代码如下:

    class
    Solution { public: vector<int> plusOne(vector<int>& digits) { int len = digits.size(); int i=0; for(i=len-1;i>=0;i--){ if(digits[i]<9){ digits[i]+=1; break;//只要最低位到最高位有一个低于9就不会产生[0]位之后的进位 } else { digits[i]=0; } }
    //各位全是9时
    if(i==-1){ digits.insert(digits.begin(), 1); } return digits; } };

    其他解法:(非常容易理解)

    class Solution {
    public:
        vector<int> plusOne(vector<int>& digits) {
            int i = digits.size() - 1;//相当于n=digits.size,i=n-1
            int carray = 1;
            while(i >= 0)
            {
                if(carray == 1)
                {
                    int sum = digits[i] + 1;
                    digits[i] = sum % 10;
                    if(sum < 10)
                    {
                        carray = 0;
                        break;
                    }
                }
                i--;
            }
    
            if(carray == 1)
            {
                digits.insert(digits.begin(), 1);
            }
    
            return digits;
        }
    };
    

      

  • 相关阅读:
    关于Js异常
    gitea windows 安装
    spring boot 错误页面配置
    mysql 常用用函数
    nginx 安装 tomcat pfx 格式证书
    git pull 报错
    maven 打 jar 包,包含 xml, 包含 额外 jar
    git clone 分支代码
    git 切换远程分支
    mycat 在 mysql 8.0 下 无法连接 bug
  • 原文地址:https://www.cnblogs.com/carsonzhu/p/4557147.html
Copyright © 2011-2022 走看看