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;
            }
            
        }
    }



  • 相关阅读:
    CSRF攻击原理
    大前端
    尊敬自己,才能拥有改变的力量
    重温尼采语录 序章
    人生的弹性 -- 观《聚宝盆》有感
    求学梦
    爱国情怀
    雾中见我
    找东西
    走在路上的感悟
  • 原文地址:https://www.cnblogs.com/dosmile/p/6444439.html
Copyright © 2011-2022 走看看