zoukankan      html  css  js  c++  java
  • [LeetCode#66]Plus One

    The problem:

    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.

    link: https://oj.leetcode.com/problems/plus-one/

    My analysis:

    This problem is a little tricky but meaningful!
    The key point we should grasp tigitly is that we only add "1"(one digit) to the number.
    The "1" have many hints in our algorithm design.
    1. we can directly set the carry's initial value as 1. (add the program's elegance!)
    2. we compute the carry for next iteration. thus, if we encounter the carry as 0, it means there would be no changes in the left partition(digits), we no longer need to proceed on.
    3. if we scan the all digits of int[] digits, we encounter no 0. it means we have an carry exceeds the significant digit.
    The tricky part is that, we could know the final value, cause we only add 1 to the original number. 9999 -> 10000.

    My solution:

    public class Solution {
        public int[] plusOne(int[] digits) {
            if (digits == null || digits.length == 0)
                return digits;
            
            int carry = 1; // assign 1 to carry directly
            int temp_digit;
            
            for (int i = digits.length - 1; i >= 0; i--) {
                    temp_digit = (digits[i] + carry) % 10;
                    carry = (digits[i] + carry) / 10;
                    digits[i] = temp_digit;
                    
                    if (carry == 0)
                        return digits;
            }
            
            int[] ret = new int[digits.length + 1];
            ret[0] = 1;
            return ret;
        }
    }
  • 相关阅读:
    随时积累随手记(持续更新...)
    Zookeeper集群搭建
    Dubbo——基于Zookeeper服务框架搭建及案例演示
    nginx配置浅析
    阿里面试回来,想和Java程序员谈一谈
    博客收藏列表
    启示录:打造用户喜爱的产品
    js深拷贝和浅拷贝
    MyBatis 总结记录
    ActiveMQ初体验
  • 原文地址:https://www.cnblogs.com/airwindow/p/4207982.html
Copyright © 2011-2022 走看看