Lintcode241-String to Integer - Naive

Given a string, convert it to an integer. You may assume the string is a valid integer number that can be presented by a signed 32bit integer (-231 ~ 231-1).

Example

Example 1:
	Input:  "123"
	Output: 123
	
	Explanation: 
	return the Integer.

Example 2:
	Input:  "-2"
	Output: -2
	
	Explanation: 
	return the Integer.


思路1:用函数
思路2: 下标由小到大,依次取String字符串的每一位。(不知为啥,这个方法提交打败的人更多)

注意:
  1. 考虑正负数;用minus变量作为flag。遍历时,循环的初始值,也和minus有关,负数要从下标1开始。
  2.  num = num * 10 + str.charAt(i) - '0'; 
    // example 1
    char
    a = '3'; char b = '5'; char c = a + b;
    // example 2
    char a = '3'; int b = 5; int c = a + b; int d = a - '0' + b;

    example 1: c = 33 + 35
    example 2: c = 33 + 5 = 38; d = 33 - 30 + 5 = 8
    所以char加减运算时,会自动转化为 ASCII码。如果想取char的实际数值,要 -'0'. (如char a = '3', 想取3,则  a - '0' )

代码(思路1):

public int stringToInteger(String str) {
    return Integer.parseInt(str);
}

 

代码(思路2):

public int stringToInteger(String str) {
        int num = 0;
        int minus = 0;
        if (str.charAt(0) == '-') {
            minus = 1;
        }
        for (int i = minus; i < str.length(); i++){
            num = num * 10 + str.charAt(i) - '0';
        }
        
        if (minus == 1) {
            return -num;
        } else{
            return num;
        }
    }

 

posted @ 2019-04-01 22:59  IreneZh  阅读(225)  评论(0编辑  收藏  举报