The line
int j = liczba.charAt(i) - 47;
Subtracts the character code of (i+1)th character liczba
by 47. Refering to an ASCII table, 47 maps to "/", whose ASCII code is one less than "0".
Note that I am assuming the following, as your code appears to be in Java.
- String indexes starts at zero i.e. first character has index 0, second character has index 1, and so on
- It seems that characters and integers can be used interchangeably, because a character is internally represented by an integer, namely, the ASCII code of the character.
- That said, the
char
type is actually an integer type, with less range
Hence, this code is to turn characters "0" to the integer 1, "1" to the integer 2, etc.
For example, when the 1st character (liczba.charAt(0)
) is the character 0
, liczba.charAt(0)
returns character '0'
, which is also equals to number 48
-- because '0'
has an ASCII code of 48.
Subtracts 48 with 47 gets 1, so it would convert character '0
' to integer 1.
However it seems that this code could cause array index out of bounds error (assuming zero-based array indexes). when a digit is '9'
, this line returns 10. This would cause an aforementioned error. Unless this code's language's array are 1-based. However, even in this case, this line
int count = digits[0];
would simply fail. This code seems to fail with the common Off by one error
I believe this line should actually read
int j = liczba.charAt(i) - 48;
so that character '0'
is converted to number 0.
If this still disturb you, you may change this line to
int j = liczba.charAt(i) - '0';
so it would be clearer. Subtract the code of '1'
and the code of '0'
gets you the integer 1, clear enough :)