String to Integer (atoi) (字符串转成整数)】

【008-String to Integer (atoi) (字符串转成整数)】【LeetCode-面试算法经典-Java实现】【所有题目目录索引】原题

  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.

题目大意

  实现一个atoi函数,将字符串转成整形   要点:考虑所有的输入情况。

解题思路

  前导字符是+或-或者没有,接下来输入的是数字,数字不能整数能表示的最大或最小数。如果超过就返回对应的最小或者最小的值。

代码实现{public int atoi(String str) {if (str == null || str.length() == 0) {;}positive = true; // 是否为正数默认为trueif (str.charAt(start) == ‘ ‘) {while (str.charAt(start) == ‘ ‘) {start++;;}}}if (str.charAt(start) == ‘-‘) { // 第一个非空白字符中-positive = false;start++;} else if (str.charAt(start) == ‘+’) {// 第一个非空白字符是+start++;} cal(str, start, true);} ;};};} else {return cal(str, start, positive);}}private int cal(String str, int start, boolean positive) {long result = 0;while (start < str.length() && str.charAt(start) >= ‘0’ && str.charAt(start) <= ‘9’) {result = result * 10 + (str.charAt(start) – ‘0’);if (positive) { // 如果是正数if (result > Integer.MAX_VALUE) {//throw new NumberFormatException(“Invalid input string: ” + str);return Integer.MAX_VALUE;}} else {if (-result < Integer.MIN_VALUE) {//throw new NumberFormatException(“Invalid input string: ” + str);return Integer.MIN_VALUE;}}start++;}if (positive) {return (int) result;} else {return (int) -result;}}}评测结果

  点击图片,鼠标不释放,拖动一段位置,释放后在新的窗口中查看完整图片。

特别说明欢迎转载,,转载请注明出处【】

唯有斯人面上簌簌流下的,是点点无声无行的热泪。

String to Integer (atoi) (字符串转成整数)】

相关文章:

你感兴趣的文章:

标签云: