Java Array to Long arrayToLong(final int[] digits)

Here you can find the source of arrayToLong(final int[] digits)

Description

eg: number = { 1, 2, 3, 4 }, returns a long = 1234 if the number correspondent of digits is bigger than Long.MAX_VALUE, so Long.MAX_VALUE is returned.

License

Open Source License

Parameter

Parameter Description
digits an array of digits [0-9]

Return

a long correspondent to the digits

Declaration

public static long arrayToLong(final int[] digits) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**/*ww  w.  ja v  a  2 s.c  o m*/
     * eg: number = { 1, 2, 3, 4 }, returns a long = 1234 if the number
     * correspondent of digits is bigger than Long.MAX_VALUE, so Long.MAX_VALUE
     * is returned.
     *
     * @param digits
     *            an array of digits [0-9]
     * @return a long correspondent to the digits
     */
    public static long arrayToLong(final int[] digits) {
        long result = 0;
        long pot = 1;
        for (int i = digits.length - 1; i >= 0; i--) {
            long partial = digits[i] * pot;
            if (Long.MAX_VALUE - result - partial > 0) {
                result += partial;
            } else {
                return Long.MAX_VALUE;
            }
            pot *= 10;
        }
        return result;
    }
}

Related

  1. arrayToLong(final byte[] array, final int start)
  2. arrayToLongString(T[] array)