I tried to be very clear with what i'm doing, it could be done in much less lines.
The algorithm is simple, i reverse the input string, then i split the number using a regex, in each match we add a comma.
If the number size module 3 is zero (for example 123456) we have to remove the last comma.
Now we restore original string order by reversing it again, 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;
}