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). ExampleExample 1: Input: "123" Output: 123 Explanation: return the Integer. Example 2: Input: "-2" Output: -2 Explanation: return the Integer. 注意:
代码(思路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; } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |