Java Abs abs(int n)

Here you can find the source of abs(int n)

Description

Computes the absolute value of a number without branching<br> The original code can be found in: http://graphics.stanford.edu/~seander/bithacks.html#IntegerAbs

License

Open Source License

Parameter

Parameter Description
n number

Return

the absolute value of this number

Declaration

public static int abs(int n) 

Method Source Code

//package com.java2s;
/*//w  w  w. j  av  a2 s.co m
 *                      ..::jDrawingLib::..
 *
 * Copyright (C) Federico Vera 2012 - 2014 <dktcoding [at] gmail>
 *
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation, either version 3 of the License, or any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

public class Main {
    /**
     * Computes the absolute value of a number without branching<br>
     * The original code can be found in:
     * http://graphics.stanford.edu/~seander/bithacks.html#IntegerAbs
     *
     * @param n number
     * @return the absolute value of this number
     */
    public static int abs(int n) {
        final int n31 = n >> 31;
        return (n + n31) ^ n31;
    }
}

Related

  1. abs(float value)
  2. abs(float value)
  3. abs(float[] items)
  4. abs(float[] values)
  5. abs(int i)
  6. abs(int number)
  7. abs(int pos, double[] array)
  8. abs(int val)
  9. abs(int val)