zoukankan      html  css  js  c++  java
  • 66. 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 int[] plusOne(int[] digits) {
            // int carry = 0;
            // int s = 1;
            // for(int i = digits.length-1;i>=0;i--){
            //     if(i==digits.length-1){
            //         s = 1;
            //     }
            //     else s=0;
            //     int cur = digits[i]+s+carry;
            //     if(cur==10){
            //         digits[i]=0;
            //         carry=1;
            //     }
            //     else{
            //         carry=0;
            //         digits[i]=cur;
            //     }
            // }
            // if(carry==1){
            //     int[] digit = new int[digits.length+1];
            //     digit[0]=1;
            //     System.arraycopy(digits,0,digit,1,digits.length);
            //         return digit;
            // }
            // else{
            //    return digits;
            // }
            int l = digits.length - 1;
            int s = 1;
            for(int i = l; i >= 0; i--){
                digits[i] += s;
                s = digits[i] / 10;
                digits[i] %= 10;
            }       
            if(s == 1){
                int[] digit = new int[l+2];
                digit[0] = 1;
                System.arraycopy(digits, 0, digit, 1, digits.length);
                return digit;
            } 
            else return digits; 
        }

    从后往前,先给末位+1,然后看是否需要进位。结束后看最后是否需要进位,若需要,使用System.arraycopy(源数组,起始位置,目的数组,起始位置,长度)。如果不需要就直接返回modified的数组

    
    
  • 相关阅读:
    微服务框架核心问题
    django restframework 全局异常处理,编写自定义custom_exception_handler
    django 异常处理中间件
    drf_yasg2 定制swagger
    redis-django
    django 权限
    django restframework 多对多的批量修改,基于逻辑删
    python3 动态绑定
    Django restframework 逻辑删除
    django restframework 多对多模型
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/11312861.html
Copyright © 2011-2022 走看看