问题:

Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases.

官方难度:

Easy

翻译:

实现atoi功能,将一个字符串转化成一个整数。

提示:仔细考虑各种可能出现的情况。

补充资料:

所谓atoi,是C语言库中的一个函数,其功能如下:

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.

函数atoi要求:

  • 丢弃第一个非空格字符串之前的所有字符串。
  • 剩余字符串接受以“+”或“-”操作符起始的数字,在遇到下一个非数值字符串之前,截取尽可能多的字符串,将其转化成数值。
  • 忽略之后遇到的非数值字符串。如果第一个非空格字符串不是数值,或者原字符串就是空格字符组成,抑或是空字符串,那么不做转换。
  • 如果不做转换,函数返回0;如果结果超出int型能表达的最大/最小值,返回整型数的最大/最小值。
  1. 先去除原字符串的前后空格,使用String.trim()方法。
  2. 处理之后的字符串,做长度为0的特殊处理,返回0。
  3. 记录第一个是“+”或“-”操作符的情况,利用一个标志位记录,在返回时使用,同时将这个位置用字符0替换,不影响之后的累加操作。
  4. 记录遇到第一个非数值字符之前的长度length。
  5. 累加数值,这里要注意两点。第一点,length作为循环退出条件,又要在操作中自减,所以需要准备一个副本;第二点,char型的字符,用于数值计算,使用array[i]-‘0’来表示当前的数值。
  6. 用long型的sum来记录累加的数值,乘以标志位置后做超出范围操作。
  7. 注意入参检查。

解题代码:

 public static int myAtoi(String str) {
if (str == null) {
throw new IllegalArgumentException("Input error");
}
// 先去空格
char[] array = str.trim().toCharArray();
// 0特殊处理
if (array.length == 0) {
return 0;
}
// 正负号标志位
int sign = 1;
long sum = 0;
if (array[0] == '+' || array[0] == '-' || (array[0] >= '0' && array[0] <= '9')) {
// 操作符置char型的'0'
if (array[0] == '+') {
array[0] = '0';
sign = 1;
} else if (array[0] == '-') {
array[0] = '0';
sign = -1;
}
// 循环确定长度
int length = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] >= '0' && array[i] <= '9') {
length++;
} else {
// 遇到非数值退出循环
break;
}
}
// length值作为退出条件,但同时又要自减,准备一个副本
int exit = length;
for (int i = 0; i < exit; i++) {
// char型的数值,转换成数值型处理
sum += (array[i] - '0') * Math.pow(10, --length);
}
// 超出范围处理
long num = sum * sign;
if (num > Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
}
if (num < Integer.MIN_VALUE) {
return Integer.MIN_VALUE;
}
return (int) num;
} else {
return 0;
}
}

myAtoi

相关链接:

https://leetcode.com/problems/string-to-integer-atoi/

https://github.com/Gerrard-Feng/LeetCode/blob/master/LeetCode/src/com/gerrard/algorithm/easy/Q008.java

PS:如有不正确或提高效率的方法,欢迎留言,谢谢!

No.008:String to Integer (atoi)的更多相关文章

  1. Q8:String to Integer (atoi)

    8. String to Integer (atoi) 官方的链接:8. String to Integer (atoi) Description : Implement atoi to conver ...

  2. leetcode:String to Integer (atoi)

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

  3. No.008 String to Integer (atoi)

    8. String to Integer (atoi) Total Accepted: 112863 Total Submissions: 825433 Difficulty: Easy Implem ...

  4. LeetCode--No.008 String to Integer (atoi)

    8. String to Integer (atoi) Total Accepted: 112863 Total Submissions: 825433 Difficulty: Easy Implem ...

  5. 《LeetBook》leetcode题解(8): String to Integer (atoi) [E]——正负号处理

    我现在在做一个叫<leetbook>的免费开源书项目,力求提供最易懂的中文思路,目前把解题思路都同步更新到gitbook上了,需要的同学可以去看看 书的地址:https://hk029.g ...

  6. 【leetcode】String to Integer (atoi)

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

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

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

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

  9. 【Leet Code】String to Integer (atoi) ——常考类型题

    String to Integer (atoi) Total Accepted: 15482 Total Submissions: 106043My Submissions Implement ato ...

随机推荐

  1. MyEclipse打开 HTML 报错Failed to create the part's controls

    拷贝代码时有时会弹出这个错误,页面仍然可以访问,但是无法编辑很郁闷.  MyEclipse默认打开编辑页面是MyEclipse visual html designer 右击html页面选择open  ...

  2. C# Azure 存储-Blob

    1. 前言 本文是根据Azure文档与本人做了验证之后写的. 如果想下载微软官网的demo, 请前往github https://github.com/Azure-Samples/storage-bl ...

  3. 蓄水池(Reservoir_sampling)抽样算法简记

    摘要 1.适用场合 2.算法简介 3.代码例子 4.Spark RangePartitioner 中的应用(待补充) 内容 1.适用场合:从包含n个项目的集合S中选取k个样本,其中n为一很大或未知的数 ...

  4. webservice返回值为Map类型的处理方法

    在写一个webservice的时候,方法的返回值是一个复杂类型,处理方法是写一个结果类(Javabean)作为返回值.想着webservice方法返回值为Map的没写过,然后就试着写了一个简单的Dem ...

  5. DPI深度包检测

    最近在读网络协议方面的论文,接触到DPI技术.博主是个小白,这里写些查到的笔记. 原文出处因为比较多,杂乱.百度文库和许多地方都有,就不贴链接了. 1. DPI 全称为"Deep Packe ...

  6. 《C#高级编程》学习总结之LINQ

    一.标准的查询操作符 标准查询操作符 说明 Where OfType<TResult> 筛选操作符定义了返回元素的条件. Select SelectMany 投射操作符用于把对象转换为另一 ...

  7. python发送邮件及附件

    今天给大伙说说python发送邮件,官方的多余的话自己去百度好了,还有一大堆文档说实话不到万不得已的时候一般人都不会去看,回归主题: 本人是mac如果没有按照依赖模块的请按照下面的截图安装 导入模块如 ...

  8. XML实体引用

    在 XML 中,一些字符拥有特殊的意义. 如果你把字符 "<" 放在 XML 元素中,会发生错误,这是因为解析器会把它当作新元素的开始. 这样会产生 XML 错误: < ...

  9. Android中实现双击事件

    需求:需要给一个view实现双击效果,查看了api,发现没有api可以调用, 于是从网上参考了一段代码. xml布局文件: <RelativeLayout xmlns:android=" ...

  10. WebService 学习之路(一):了解并使用webService

    webService主要用于向其他系统提供接口以便调用,系统间可能开发语言等完全不同,根据约定的接口规范,调用者传递相关参数进行接口调用,服务方根据传入的条件进行业务处理并进行结果返回. webSer ...