Here you can find the source of abs(int n)
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
Parameter | Description |
---|---|
n | number |
public static int abs(int n)
//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; } }