Created
January 28, 2016 15:25
-
-
Save BrandonLMorris/68a91fc1e066eb38f774 to your computer and use it in GitHub Desktop.
Pointing out an interesting quirk with Java's Math.abs() where it actually returns a negative number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
/** | |
* Problem statement: Given a number (that is guaranteed to fit within a 32 bit | |
* two's compliment integer), print the absolute value of that number. | |
* | |
* The catch: A two's compliment signed integer has a larger range for negative | |
* numbers than it does positive. So simply returning Math.abs() on the input | |
* won't always work if the input is Integer.MIN_VALUE (-2147483648). | |
*/ | |
public class ConvertToPositive { | |
public static void main(String[] args) { | |
Scanner in = new Scanner(System.in); | |
// This will NOT work if input is Integer.MIN_VALUE (-2147483648) | |
// System.out.println(Math.abs(in.nextInt())); | |
// Method one: Handle the edge case specifically | |
/**/ // Add space to comment out | |
int input = in.nextInt(); | |
if (input == Integer.MIN_VALUE) { | |
System.out.println("2147483648"); | |
} else { | |
System.out.println(Math.abs(input)); | |
} | |
/**/ | |
// Method two: just use longs and not ints | |
/** / // Delete that space to uncomment | |
long input = in.nextLong(); | |
System.out.println(Math.abs(input)); | |
/**/ | |
// Method three: just use strings | |
/** / // Delete that space to uncomment | |
String input = in.next(); | |
if (input.charAt(0) == '-') { | |
System.out.println(input.substring(1)); | |
} else { | |
System.out.println(input); | |
} | |
/**/ | |
} | |
} | |
/* | |
* The class name of this program is somewhat misleading, since zero is | |
* neither a positive nor negative number, mathematically speaking. | |
* However, I didn't feel like naming it "ConvertToNonNegative", even | |
* though that is technically more accurate. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment