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;
        }
    }

 

转载于:https://www.cnblogs.com/Jessiezyr/p/10639872.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值