I'm trying to find the product of all digits in a number, which I have stored as a string (due to int and long length limits).
So the number looks like this:
final String number = "1234567898765432123......etc"
If I use this code, it works:
product *= number.charAt(i + j) - '0';
It doesn't if I remove the '0'.
I got this code from another online resource. Can someone explain what the '0' does?
'0' is the char value of zero. When you write a string, you're writing an array of 'char' datatypes which the compiler translates into ASCII values (which have a corresponding decimal number value).
When we talk about Strings in Java, we can imagine them as arrays of characters, and they are, but in Java, they also object. An empty Java String is considered as the not null String that contains zero characters, meaning its length is 0.
In computer programming, a null-terminated string is a character string stored as an array containing the characters and terminated with a null character (a character with a value of zero, called NUL in this article).
null means that a variable contains a reference to a space in memory that does not contain an object. 0 is a numeric data type with a value of 0. Nothing doesn't really exist, however I think you may be viewing this as an empty String "" which is simply a String data type that does not contain a value.
Ascii characters are actually numbers. And 0 .. 9
digits are numbers starting from decimal 48 (0x30 hexadecimal).
'0' is 48
'1' is 49
...
'9' is 57
So to get the value of any character digit, you can just remove the '0', ie 48.
'1' - '0' => 1
49 - 48 => 1
If you don't remove '0' (48) the total sum will be over by 48 * numberOfDigits
.
See an ascii table to locate digits in it.
Note that '0'
is the character 0
, not the string "0"
containing the character '0'
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With