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

    将一个整型数组当成一个整数,将该数加一后返回所得新的数组。

    所要考虑的是进位和溢出问题,和Add Binary这道题类似,从低位逐位和进位相加,直至不产生进位为止,假若最高位产生进位,则组要new一个新的数组,size+1,并将新数组第一位置1,后面接上刚刚加完1的数组。

    完整代码:

    public class Solution {
        public int[] plusOne(int[] digits) {
            int size = digits.length;
            int carry = 1;
            for(int i=size-1;i>=0;i--){
                int sum = digits[i]+carry;
                if(sum>=10){
                    carry = 1;
                    digits[i] = sum-10;
                }
                else{
                    carry = 0;
                    digits[i] = sum;
                    break;
                }
            }
            if(carry==1){
                int[] re = new int[size+1];
                re[0] = 1;
                for(int j = 0;j<size;j++){
                    re[j+1] = digits[j];
                }
                return re;
            }
            return digits;
        }
    }
  • 相关阅读:
    ubuntu18.04 常用命令
    docker常用命令
    git
    y7000 intel nvidia 双显卡安装Ubuntu16.04
    linux中fork() 函数详解
    理解GBN协议
    C++ sort
    最近点对-分治
    方便查看 linux/kernel/system_call.s
    方便查看 linux/kernel/asm.s
  • 原文地址:https://www.cnblogs.com/mrpod2g/p/4273239.html
Copyright © 2011-2022 走看看