Help me understand how this code works. It essentially adds a comma to the string of numbers. Therefore, if the user enters a number from 1 to 3 digits, it does not change. For a four-digit number, it adds a comma, so
- 1111 becomes 1.111
- 11111 becomes 11.111
- 111111111 becomes 11,111,111
etc. Here is the code:
private String addCommasToNumericString (String digits)
{
String result = "";
int len = digits.length();
int nDigits = 0;
for (int i = len - 1; i >= 0; i--)
{
result = digits.charAt(i) + result;
nDigits++;
if (((nDigits % 3) == 0) && (i > 0))
{
result = "," + result;
}
}
return (result);
}
I will explain that I understand about it
The loop forbasically calculates the length of the number that the user wrote so as not to put a comma before the first number (for example, 1111). And although it is iless than the length of the string, it subtracts 1.
resultreturns a char at a position i, as it counts down, it returns the characters “opposite” from right to left.
nDigits 1 0 .
, , : if ("nDigits % 3) == 0.
, if , :
nDigits 1 - nDigits++ for, , ? , 4 5 , 1 (1,111 - 11,111)?