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



  • 相关阅读:
    人生中最重要的三位老师
    自我介绍
    秋季学习总结
    第五周学习总结
    第四周总结
    第三周基础作业
    判断上三角矩阵
    第二周作业及编程总结
    求最大值及其下标
    查找整数
  • 原文地址:https://www.cnblogs.com/dosmile/p/6444439.html
Copyright © 2011-2022 走看看