How does Integer.parseInt(string) actually work?

2019-01-10 23:07发布

Was asked this question recently and did not know the answer. From a high level can someone explain how Java takes a character / String and convert it into an int.

Many thanks

Karl

Edit: Would also be good to know if other languages do a similar sort of thing as well.

7条回答
Fickle 薄情
2楼-- · 2019-01-10 23:45

this is my simple implementation of parse int

public static int parseInteger(String stringNumber) {
    int sum=0;
    int position=1;
    for (int i = stringNumber.length()-1; i >= 0 ; i--) {
       int number=stringNumber.charAt(i) - '0';
       sum+=number*position;
       position=position*10;

    }
    return sum;
}
查看更多
登录 后发表回答