Skip to content

Instantly share code, notes, and snippets.

@gabhi
Created June 26, 2014 20:33
Show Gist options
  • Save gabhi/74f3d248185b61861d7e to your computer and use it in GitHub Desktop.
Save gabhi/74f3d248185b61861d7e to your computer and use it in GitHub Desktop.
ITOA in java
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