洞察探索如何利用兼容微信生态的小程序容器,实现跨平台开发,助力金融和车联网行业的数字化转型。
676
2022-11-11
8. String to Integer (atoi)
Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
Update (2015-02-10): The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.
spoilers alert… click to show requirements for atoi.
public class Solution { public int myAtoi(String str) { // 1. null or empty string if (str == null || str.length() == 0) return 0; // 2. whitespaces str = str.trim(); // 3. +/- sign boolean positive = true; int i = 0; if (str.charAt(0) == '+') { i++; } else if (str.charAt(0) == '-') { positive = false; i++; } // 4. calculate real value double tmp = 0; for ( ; i < str.length(); i++) { int digit = str.charAt(i) - '0'; if (digit < 0 || digit > 9) break; // 5. handle min & max if (positive) { tmp = 10*tmp + digit; if (tmp > Integer.MAX_VALUE) return Integer.MAX_VALUE; } else { tmp = 10*tmp - digit; if (tmp < Integer.MIN_VALUE) return Integer.MIN_VALUE; } } int ret = (int)tmp; return ret; } }
Java2
class Solution { public int myAtoi(String str) { str = str.trim(); int retVal = 0; int startIndex = 0; int sign = 1; if(str.equals("")) { return 0; } startIndex = str.charAt(0) == '-' || str.charAt(0) == '+' ? 1 : 0; sign = str.charAt(0) == '-' ? -1 : 1; for(int i = startIndex ; i < str.length() ; i++) { char c = str.charAt(i); if('0' <= c && c <= '9') { if(retVal > (Integer.MAX_VALUE - (c - '0')) / 10) return sign > 0 ? Integer.MAX_VALUE : Integer.MIN_VALUE; retVal = retVal * 10 + (c - '0'); } else { break; } } return sign * retVal; }}
JS
/** * @param {string} str * @return {number} */var myAtoi = function(str) { str = str.trimLeft(); // remove whitespace from beginning of string if (!/[\d+-]/.test(str[0])) return 0; // if first character is not +,- or a digit const number = Number(str.match(/[+-]?\d*/)); // regex means: optional(+,-) follows by zero (case " + 514 " => expect 0) or more digits if (Number.isNaN(number)) return 0; // invalid integral number. eg: " + 514" => expect 0 (Number('+') => NaN) const MAX_INT = 2 ** 31 - 1; const MIN_INT = - (2 ** 31); if (number < MIN_INT) return MIN_INT; if (number > MAX_INT) return MAX_INT; return number;};
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~