What?
Many programming languages, both practical and esoteric, have functions, methods, etc to convert a given string to a decimal number. This is how the process might work:
- For each character in the given string.
- Take the character's ASCII value and subtract it by 48.
- Multiply the output value by 10. (The output at the first iteration is 0)
- Add the subtracted ASCII value to the output.
Let us do this process for the string "109"
:
The ASCII value of
1
is 49. Subtract it by 48, and we get 1. We multiply the output by 10, we get 0. Finally, we add 1 to 0 and get one.Next, we subtract
0
's ASCII value (48) by 48, we get 0. We multiply 1 by 10, we get 10. Nothing happens when we add 0.Then we subtract
9
's ASCII value (57) by 48, we get 9. We multiply 10 by 10 and get 100. We add 9 to 100 and get 109.
There, we successfully converted "109"
to 109! It is just as simple!
The problem is that most languages do not like it when the converting string has non-digital characters (characters with an ASCII value not in the range 48-57 inclusive). They would most likely throw some nasty errors or exceptions at us.
How 'bout we ignore that!
Task
Given a printable string from STDIN (you can assume that \$1 ≤ \text{Input Length} ≤ 10\$), implement a program or function to badly convert it to an integer according to the above steps, and output or return it back.
Strings can contain whitespace characters (Spaces, tabs and linefeeds).
For another example string "Hi!"
:
The ASCII value of
H
is 72:
72 - 48 = 24
0 * 10 = 0
0 + 24 = 24
The ASCII value of
i
is 105:
105 - 48 = 57
24 * 10 = 240
240 + 57 = 297.
The ASCII value of
!
is 33:
33 - 48 = -15
297 * 10 = 2970
2970 + -15 = 2955
This means that "Hi!"
converted to an integer is 2955!
Standard I/O rules apply.
Note: if your language does not support input, feel free to tell me in your answers (you can put the "input" strings in your source code)!
More test cases
STDIN Output
"123456789" -> 123456789
"0123456789" -> 123456789
"-12345" -> -287655
"Lorem" -> 350191
"Ipsum" -> 321451
"AAAAAAAA" -> 188888887
" " -> -177777776
"A" -> 17
" " -> -16
"
" -> -38
Standard code-golf rules apply!
ASCII value - 48
even though it actually refers to the previous step. Just my 2c$, feel free to ignore it. \$\endgroup\$