加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Lintcode241-String to Integer - Naive

发布时间:2020-12-14 04:35:19 所属栏目:大数据 来源:网络整理
导读: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: 123Explanation: return the Integer.Example 2

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读