Leetcode-66. Plus One


Total Accepted: 78150
  Total Submissions: 244950  Difficulty: Easy

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.


主要解题思路:不论carrier为多少,当前的值应为(digits[i]+carrier)%10,而carrier的值应该被重新赋为 (digits[i]+carrier)/10。
然后分两种情况考虑,无需进位的则直接返回,需要进位的只有一种情况:因为carrier==1的特殊性,全为9的情况,在这种情况下结果数组的位数比输入数组多一位。即输入{9, 9}输出{1, 0, 0}。
代码如下:
p
public class Solution {
    public int[] plusOne(int[] digits) {
     int carrier = 1;
     int n = digits.length-1;
     for(int i = n; i>=0; i--){
         int temp = digits[i]+carrier;
         digits[i] = temp%10;
         carrier = temp/10;
     }
     //如果没有进位,则digits为答案,代码到此为止都没有考虑carrier为1的特殊性。
     if(carrier == 0) return digits;
     int[] result = new int[n+2];
     //这部分代码考虑了carrier为1的特殊性。加1进位的可能性只有第一位为1,后面都是0.比如[9,9]到[1,0,0].array默认值为0,因此只需要初始化第一位。
     result[0] = 1;
     return result;
    }
}


还有一种直接从carrier==1来考虑问题的做法,先check数组是不是全9,多循环了一遍digits数组,没有上一组做法更优。做法: 只须从数组尾部开始,若当前位是9则向前一位进位,小于9则直接将当前位加一返回即可。
package com.cwind.leetcode.math;

/**
 * Created with IntelliJ IDEA.
 * User: Cwind
 * Date: 2015/7/1
 * Email: billchen01@163.com
 * #66 - Easy
 */
public class PlusOne {

    public int[] plusOne(int[] digits) {
        if(digits == null){
            return null;
        }
        // check if it is all 9
        boolean allNine = true;
        for(int digit : digits){
            if(digit!=9){
                allNine = false;
            }
        }

        if(allNine){
            int result[] = new int[digits.length+1];
            result[0] = 1;
            return result;
        }else {
            for(int i=digits.length-1;i>=0;i--){
                if(digits[i]<9){
                    digits[i]++;
                    break;
                }else{
                    digits[i]=0;

                }
            }
        }
        return digits;
    }

    public static void main(String[] args){
        PlusOne tester = new PlusOne();
        int[] input = {1,2,3,9};
        int[] output = tester.plusOne(input);
        for(int i:output){
            System.out.print(i);
        }
        int[] input2 = {9,9};
        output = tester.plusOne(input2);
        for(int i:output){
            System.out.print(i);
        }
    }
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值