Ok, code reviewers, I want you to pick my code apart and give me some feedback on how I could make it better or more simple.
public final class StringValueOf {
private StringValueOf () {}
// note that int max value is 10 digits
final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999,
99999999, 999999999, Integer.MAX_VALUE };
private final static char[] DigitOne = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
};
private final static char[] DigitTens = {
'0', '0', '0', '0', '0', '0', '0', '0', '0', '0',
'1', '1', '1', '1', '1', '1', '1', '1', '1', '1',
'2', '2', '2', '2', '2', '2', '2', '2', '2', '2',
'3', '3', '3', '3', '3', '3', '3', '3', '3', '3',
'4', '4', '4', '4', '4', '4', '4', '4', '4', '4',
'5', '5', '5', '5', '5', '5', '5', '5', '5', '5',
'6', '6', '6', '6', '6', '6', '6', '6', '6', '6',
'7', '7', '7', '7', '7', '7', '7', '7', '7', '7',
'8', '8', '8', '8', '8', '8', '8', '8', '8', '8',
'9', '9', '9', '9', '9', '9', '9', '9', '9', '9',
};
private static int stringSize(int x) {
for (int i = 0; ; i++) {
if (x <= sizeTable[i]) {
return i + 1;
}
}
}
private static void getChars (char[] buf, int size, int i) {
int charPos = size - 1;
if (i < 0) {
i = -i;
}
while (i >= 10) {
int r = i % 100;
i = i / 100;
buf[charPos--] = DigitOne[r];
buf[charPos--] = DigitTens[r];
}
if (i > 0) {
buf[charPos--] = DigitOne[i];
}
if (charPos == 0) {
buf[charPos] = '-';
}
}
public static String valueOf(int i) {
if (i == Integer.MAX_VALUE) {
return "-2147483648";
}
int size = (i < 0) ? stringSize(-i ) + 1 : stringSize(i);
char[] buf = new char[size];
buf.toString();
getChars(buf, size, i);
/**
* There are 2 ways to convert a char into string.
* 1. buf.toString()
* 2. String(buf)
*
* but we should use String(buf) because:
* 1. Mostly buf.toString would internally call String(buf)
* 2. Integer class uses new String.
*/
return new String(buf);
}
public static void main(String[] args) {
System.out.println(valueOf(101));
System.out.println(valueOf(-2010));
}
}
buf.toString()
doesn't do anything. Also, don't you mean to test forInteger.MIN_VALUE
and return-2147483648
? \$\endgroup\$