Created
June 26, 2014 20:33
-
-
Save gabhi/74f3d248185b61861d7e to your computer and use it in GitHub Desktop.
ITOA in java
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
public class ITOA { | |
public static String convert(int x, int base) { | |
boolean negative = false; | |
String s = ""; | |
if (x == 0) | |
return "0"; | |
negative = (x < 0); | |
if (negative) | |
x = -1 * x; | |
while (x != 0) { | |
s = (x % base) + s; // add char to front of s | |
x = x / base; // integer division gives quotient | |
} | |
if (negative) | |
s = "-" + s; | |
return s; | |
} // convert | |
public static void main(String[] args) // test | |
{ | |
int x = 16; | |
int base = 2; | |
System.out.println(convert(x, base)); | |
base = 10; | |
System.out.println(convert(x, base)); | |
} | |
} // end class itoa |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment