I tried to be very clear with what I am doing, it can do much less lines.
The algorithm is simple, I change the input line, and then break the number with a regular expression, in each match we add a comma.
If the module of size 3 is zero (e.g. 123456), we must remove the last comma.
Now we restore the original row order, again changing it, and voilá.
public String insertCommas(Integer largeNumber) {
String result;
String reversedNum = new StringBuilder(""+largeNumber).reverse().toString();
String reversedResult = "";
Pattern pattern = Pattern.compile("\\d{3}");
Matcher matcher = pattern.matcher(reversedNum);
int lastIndex = reversedNum.length();
while(matcher.find()){
reversedResult += matcher.group()+",";
lastIndex = matcher.end();
}
String remaining = reversedNum.substring(lastIndex);
reversedResult += remaining;
result = new StringBuilder(reversedResult).reverse().toString();
if(remaining.isEmpty()){
result = new StringBuilder(reversedResult).reverse().toString().substring(1);
}else{
result = new StringBuilder(reversedResult).reverse().toString();
}
return result;
}
source
share