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的数组

    
    
  • 相关阅读:
    js原生图片拼图Demo
    display:inline-block在ie7下的解决办法
    Apollo 配置中心部署注意事项
    chrony 时间同步配置
    IPv6基础介绍
    Rabbitmq 报错 nodedown
    Maven 私服你应该不陌生吧,可你会用 Artifactory 搭建吗?
    你 MySQL 中重复数据多吗,教你一招优雅的处理掉它们!
    MySQL 数据库的基本使用
    自建 yum 源
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/11312861.html
Copyright © 2011-2022 走看看