Java Number Minus minusExact(long a, long b)

Here you can find the source of minusExact(long a, long b)

Description

minus Exact

License

Apache License

Parameter

Parameter Description
a A long value.
b A long value.

Exception

Parameter Description
ArithmeticException if the mathematical result of a-b is not in [Long.MIN_VALUE,Long.MAX_VALUE] range.

Return

The mathematical result of a-b.

Declaration

public static long minusExact(long a, long b) 

Method Source Code

//package com.java2s;
/*//from w w w.ja  v  a2 s . c  o  m
 * Copyright 2012 Jeff Hain
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

public class Main {
    /**
     * @param a An int value.
     * @param b An int value.
     * @return The mathematical result of a-b.
     * @throws ArithmeticException if the mathematical result of a-b is not in [Integer.MIN_VALUE,Integer.MAX_VALUE] range.
     */
    public static int minusExact(int a, int b) {
        if ((a ^ b) >= 0) { // test if a and b signs are identical
            return a - b;
        } else {
            int diff = a - b;
            if ((a ^ diff) < 0) {
                throw new ArithmeticException("overflow: " + a + "-" + b);
            } else {
                return diff;
            }
        }
    }

    /**
     * @param a A long value.
     * @param b A long value.
     * @return The mathematical result of a-b.
     * @throws ArithmeticException if the mathematical result of a-b is not in [Long.MIN_VALUE,Long.MAX_VALUE] range.
     */
    public static long minusExact(long a, long b) {
        if ((a ^ b) >= 0) { // test if a and b signs are identical
            return a - b;
        } else {
            long diff = a - b;
            if ((a ^ diff) < 0) {
                throw new ArithmeticException("overflow: " + a + "-" + b);
            } else {
                return diff;
            }
        }
    }
}

Related

  1. minusDayOfWeek(int dow, long days)
  2. minusEquals(double[] w, double v)
  3. minusEquals(int[] vals, int min)
  4. minusEqualsInverse(double[] w, double[] v, double a)
  5. minusExact(final int a, final int b)
  6. minusPercent(float maxValue, float minusValue)
  7. minusPIO2(final double angRad)