/**
* Source : https://oj.leetcode.com/problems/string-to-integer-atoi/
*
* Created by lverpeng on 2017/7/4.
*
* 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.
*
*/
public class IntegerParser { /**
* 将字符串转化为int
* 考虑各种输入:
* 输入包含非数字
* 超出int范围
* 可能是负数
*
* @param str
* @return
*/
public int parse (String str) throws Exception {
if (str == null || str.length() == 0) {
return 0;
}
int result = 0;
boolean flag = true;
if (str.charAt(0) == '-') {
flag = false;
str = str.substring(1);
} else if (str.charAt(0) == '+') {
flag = true;
str = str.substring(1);
}
for (int i = 0; i < str.length(); i++) {
if (!isdDigit(str.charAt(i))) {
throw new IllegalArgumentException("is not a number");
}
if (result > Integer.MAX_VALUE / 10 || result < Integer.MIN_VALUE / 10) {
throw new Exception("overflow");
}
result = result * 10 + str.charAt(i) - 48;
}
if (!flag) {
result = 0 - result;
}
return result;
} private boolean isdDigit (char c) {
if (c >= 48 && c <= 57) {
return true;
}
return false;
} public static void main(String[] args) throws Exception {
IntegerParser parser = new IntegerParser();
System.out.println(parser.parse("123"));
System.out.println(parser.parse("+123"));
System.out.println(parser.parse("-123"));
System.out.println(parser.parse("123ABC"));
}
}

leetcode — string-to-integer-atoi的更多相关文章

  1. LeetCode: String to Integer (atoi) 解题报告

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

  2. [LeetCode] String to Integer (atoi) 字符串转为整数

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

  3. [Leetcode] String to integer atoi 字符串转换成整数

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

  4. [LeetCode] String to Integer (atoi) 字符串

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

  5. [Leetcode]String to Integer (atoi) 简易实现方法

    刚看到题就想用数组做,发现大多数解也是用数组做的,突然看到一个清新脱俗的解法: int atoi(const char *str) { ; int n; string s(str); istrings ...

  6. [LeetCode]String to Integer (atoi)

    题意:字符串转正数 原题来自:https://leetcode.com/problems/string-to-integer-atoi/ 分析: <程序员面试宝典>上出现的面试题,主要是考 ...

  7. leetcode String to Integer (atoi) python

    class Solution(object): def myAtoi(self, str): """ :type str: str :rtype: int "& ...

  8. 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 ...

  9. Kotlin实现LeetCode算法题之String to Integer (atoi)

    题目String to Integer (atoi)(难度Medium) 大意是找出给定字串开头部分的整型数值,忽略开头的空格,注意符号,对超出Integer的数做取边界值处理. 方案1 class ...

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

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

随机推荐

  1. Linux驱动之同步、互斥、阻塞的应用

    同步.互斥.阻塞的概念: 同步:在并发程序设计中,各进程对公共变量的访问必须加以制约,这种制约称为同步. 互斥机制:访问共享资源的代码区叫做临界区,这里的共享资源可能被多个线程需要,但这些共享资源又不 ...

  2. C++学习札记(1)

    指针 按别名传递 下面是个例子: #include <iostream> using namespace std; void swap(int &a,int &b) { i ...

  3. Sort Array By Parity II LT922

    Given an array A of non-negative integers, half of the integers in A are odd, and half of the intege ...

  4. xbee/xbeeRPOS1、xbee/xbeePROS2C802.15.4/Digimesh功能方法

    Digi XBee 802.15.4的第一个版本也称为S1,是基于Freescale的无线收发器片子设计的.最新的802.15.4模块(内部称号S1B)采用和Digi ZigBee模块相同SOC芯片设 ...

  5. LOJ-10105(欧拉回路模板,套圈法,递归)

    题目链接:传送门 思路: (1)用邻接表存储有向图和无向图,有向图和无向图的每条边均站两个单元,无向图有正向边和反向边的区分. (2)有向图有欧拉回路:所有点的入度=出度: 无向图有欧拉回路:所有点的 ...

  6. python模块:xml.etree.ElementTree

    """Lightweight XML support for Python. XML is an inherently hierarchical data format, ...

  7. Linux连不上校园网怎么办?

    原本,在我们学校我只要连上WiFi打开浏览器, 它就会自动重定向到校园网登录的界面.但是今天浏览器并没有自己打开登录页面,一直在加载.于是我想直接登录路由器,在地址栏输入192.168.0.1,结果它 ...

  8. salt 配置管理

    索引 saltstack入门 salt state sls 描述文件 saltstack配置管理高级功能 saltstack入门 192.168.86.3 salt 修改 [root@Zabbix-s ...

  9. String str.trim()

    String.trim() 方法不仅仅是去除字符串两端的空格字符,它能去除25种字符: ('/t', '/n', '/v', '/f', '/r', ' ', '/x0085', '/x00a0', ...

  10. 【洛谷4070】 [SDOI2016]生成魔咒(SAM)

    传送门 洛谷 Solution 考虑要求的是什么,前缀的本质不同的字符串个数? 如果只要求一个串那么显然答案是\(\sum_{i=1}^{tot}len[i]-len[fa[i]]\)(实际上这个并不 ...