2

Recently while taking some algorithm practise at leetcode i came across a solution, i understood everything except the part where the user converts an element in a string to an integer, look at the code below. Hopefully someone can explain this to me. Thanks for replies in advnace.

a := 234
b := strconv.Itoa(a)
c := int(b[0]-48) // why do we subtract 48?

2 Answers 2

5

48 is the code of the '0' character in the ASCII table.

Go stores strings as their UTF-8 byte sequences in memory, which maps characters of the ASCII table one-to-one to their code.

The digits in the ASCII table are listed contiguously, '0' being 48. So if you have a digit in a string, and you subtract 48 from the character's code, you get the digit as a numeric value.

Indexing a string indexes its bytes, and in your case b[0] is the first byte of the b string, which is 2. And '2' - 48 is 2.

For example:

fmt.Println('0' - 48)
fmt.Println('1' - 48)
fmt.Println('2' - 48)
fmt.Println('3' - 48)
fmt.Println('4' - 48)

This outputs (try it on the Go Playground):

0
1
2
3
4
0
2

“b” is a string “234”, a string is a slice of rune therefore b[0] is a byte/rune, in this case a value of 50 which is the decimal value of a “2” in ascii. So “c” will be 50-48=2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.