问题描述:

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.

Requirements for atoi:

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

解题思路:

首先调用trim方法除去字符串两边的空白字符。然后从开头读起,如果开头为‘+’,表明该值为正数;如果开头为‘-’,表明该值为负数;如果第一个读到的是‘+’或者‘-’,则从第二个开始读,否则仍然从第一个读起。下面开始一直往后读直到字符串结束。如果在读的过程中读到了除字符’0‘-’9'以外的数字,那么跳出循环,返回计算好的值,否则,不停的计算累加值。

代码如下:

public class Solution {
public int myAtoi(String str) {
boolean negative = false;
int i = 0;
int result = 0;
int digit; if (str == null || str.length() == 0)
return 0;
str = str.trim();
if (str.length() == 0)
return 0;
if (str.charAt(0) == '-' || str.charAt(0) == '+') {
if (str.charAt(0) == '-') {
negative = true;
}
i++;
}
while (i < str.length()) {
if (str.charAt(i) > '9' || str.charAt(i) < '0')
break;
digit = str.charAt(i) - '0';
if (!negative && result > (Integer.MAX_VALUE - digit) / 10)
return Integer.MAX_VALUE;
else if (negative && result > -((Integer.MIN_VALUE + digit) / 10))
return Integer.MIN_VALUE;
else {
result = result * 10 + digit;
i++;
}
}
return negative ? -result : result;
}
}

Java [leetcode 8] String to Integer (atoi)的更多相关文章

  1. Leetcode 8. String to Integer (atoi) atoi函数实现 (字符串)

    Leetcode 8. String to Integer (atoi) atoi函数实现 (字符串) 题目描述 实现atoi函数,将一个字符串转化为数字 测试样例 Input: "42&q ...

  2. leetcode day6 -- String to Integer (atoi) &amp;&amp; Best Time to Buy and Sell Stock I II III

    1.  String to Integer (atoi) Implement atoi to convert a string to an integer. Hint: Carefully con ...

  3. 【leetcode】String to Integer (atoi)

    String to Integer (atoi) Implement atoi to convert a string to an integer. Hint: Carefully consider ...

  4. [leetcode] 8. String to Integer (atoi) (Medium)

    实现字符串转整形数字 遵循几个规则: 1. 函数首先丢弃尽可能多的空格字符,直到找到第一个非空格字符. 2. 此时取初始加号或减号. 3. 后面跟着尽可能多的数字,并将它们解释为一个数值. 4. 字符 ...

  5. Leetcode 8. String to Integer (atoi)(模拟题,水)

    8. String to Integer (atoi) Medium Implement atoi which converts a string to an integer. The functio ...

  6. [LeetCode][Python]String to Integer (atoi)

    # -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com'https://oj.leetcode.com/problems/string- ...

  7. 【JAVA、C++】 LeetCode 008 String to Integer (atoi)

    Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. ...

  8. 【LeetCode】String to Integer (atoi) 解题报告

    这道题在LeetCode OJ上难道属于Easy.可是通过率却比較低,究其原因是须要考虑的情况比較低,非常少有人一遍过吧. [题目] Implement atoi to convert a strin ...

  9. LeetCode 8. String to Integer (atoi) (字符串到整数)

    Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. ...

随机推荐

  1. 【BZOJ】【1115】【POI2009】石子游戏KAM

    博弈论 这个题……一看就觉得很捉急啊= =肿么办? 灵光一现:差分一下~ 那么我们看一下差分以后,从第 i 堆中拿走 k 个石子变成了:a[i]-=k; a[i+1]+=k; 嗯这就转化成了阶梯博弈! ...

  2. hdu 2196

    树形dp 本文出自   http://blog.csdn.net/shuangde800 题目传送门 题意: 给出一棵树,求离每个节点最远的点的距离 思路: 把无根树转化成有根树分析, 对于上面那棵树 ...

  3. CF 295A Greg and Array (两次建树,区间更新,单点查询)

    #include <iostream> #include <stdio.h> #include <string.h> #include <algorithm& ...

  4. MVC中SelectList和@Html.DropDownList("MainDuty_UserId","请选择")的运用

    Models.Project model = projectdb.dbSet.SingleOrDefault(e => e.Project_ID == id);            ViewB ...

  5. 防止注入网上查了下用SqlParameter可以,那SqlParameter处理单引号时候是自动转义了吗

    String sql = String.Format(); SqlCommand com = new SqlCommand(sql, con); 一般而言,把 一个单引号,替换成 两个单引号就可以了.

  6. Android Studio删除工程里面无用的代码和资源

    如果你是一个经常开发android应用程序或者做android维护项目的人,我想说你对我谈论的这个话题,一定会感兴趣的. 因为只有做到了这两点,你的项目生成的apk包才会更小,而不是随着你的开发和维护 ...

  7. 获取其它进程窗口中的状态栏信息(FindWindowEx GetWindowThreadProcessId OpenProcess SendMessage轮番轰炸)

    HWND hWnd = ::FindWindow(NULL, _T("XXXXX")); if(NULL == hWnd) { return ; } HWND hWndStatus ...

  8. VC程序查错之内存访问异常

    作者:langouster 先来看下面这张图,相信很多程序员都见过类似. ---------------------------test1.exe - 应用程序错误------------------ ...

  9. 使用phantomjs对页面进行截图

    本文章参考了使用phantomjs操作DOM并对页面进行截图需要注意的几个问题 及 phantomjs使用说明 这两篇文章,初次接触phantomjs的童鞋可以去看下这两篇原文 在学习中可以看下 ph ...

  10. OpenCV码源笔记——RandomTrees (一)

    OpenCV2.3中Random Trees(R.T.)的继承结构: API: CvRTParams 定义R.T.训练用参数,CvDTreeParams的扩展子类,但并不用到CvDTreeParams ...