zoukankan      html  css  js  c++  java
  • 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.

    解决思路

    检查digits数组中是否全是9,如果全是,直接返回手动计算的结果即可;

    否则,数组遍历做加法。 

    程序

    public class Solution {
        public int[] plusOne(int[] digits) {
            if (digits == null || digits.length == 0) {
                return new int[0];
            }
            
            boolean isLonger = checkDigits(digits);
            int len = digits.length;
            
            if (isLonger) {
                int[] res = new int[len + 1];
                res[0] = 1;
                return res;
            }
            
            int[] res = new int[len];
            int i = len - 1;
            int c = 1;
            while (i >= 0) {
                int s = digits[i] + c;
                int d = s % 10;
                c = s / 10;
                res[i] = d;
                --i;
            }
            
            return res;
        }
        
        private boolean checkDigits(int[] digits) {
            for (int d: digits) {
                if (d != 9) {
                    return false;
                }
            }
            return true;
        }
    }
    

      

  • 相关阅读:
    HDU2059(龟兔赛跑)
    pat 1012 The Best Rank
    pat 1010 Radix
    pat 1007 Maximum Subsequence Sum
    pat 1005 Sign In and Sign Out
    pat 1005 Spell It Right
    pat 1004 Counting Leaves
    1003 Emergency
    第7章 输入/输出系统
    第六章 总线
  • 原文地址:https://www.cnblogs.com/harrygogo/p/4672370.html
Copyright © 2011-2022 走看看