8. String to Integer (atoi)

来源:互联网 发布:安卓 gba 模拟器 知乎 编辑:程序博客网 时间:2024/06/07 14:53

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;      }  }  
原创粉丝点击