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.

    //思想类似于前两天的add binary与add two numbers
    //数组中,高位在左,低位在右,故反向遍历并维护进位
    public class Solution {
        public int[] plusOne(int[] digits) {
            
            if(digits==null || digits.length==0){
                return null;
            }
            
            int carry = 1;     //在第一次循环时,充当one的角色,以后作为进位标志位
            int index = digits.length - 1;
            
            while(index >= 0){
                int temp = digits[index] + carry; 
                int newDigit = temp % 10;
                carry = temp / 10;
                
                digits[index] = newDigit;
                index--;
            }
            
            if(carry > 0){       //因仅仅加1,若此时还有进位,则原数组毕为9999..形式
                int[] result = new int[digits.length+1];
                result[0] = 1;   //新建个扩充数组,且首位为1即可
                return result;
            }else{
                return digits;
            }
            
        }
    }



  • 相关阅读:
    事件溯源的使用实例
    CQRS With Axon
    maven打包带依赖
    MongoDB Query语法和工具
    docker 在外部指定参数变量 spring
    logger 过滤部分类的logger
    Nginx ServerName指令
    Nginx 处理Http请求简单流程
    Listen 指令
    Nginx 配置
  • 原文地址:https://www.cnblogs.com/dosmile/p/6444439.html
Copyright © 2011-2022 走看看