8. String to Integer (atoi)
来源:互联网 发布:js的单选按钮的事件 编辑:程序博客网 时间:2024/06/05 14:23
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.
问题描述:atoi (表示 ascii to integer)是把字符串转换成整型数的一个函数,注意整数溢出问题。
分析:输入的字符串有以下几种情况考虑:
(1)当输入的字符串长度为0或者去掉空格后长度为0时,返回0;
(2)当输入的字符串第一个字符为“+”、“-”,变量flag记录转换后的整数符号。为“+”时,flag=1;为“-”时,flag=-1;
(3)当字符为数值时,即(s.charAt(i) - '0')>=0 && (s.charAt(i) - '0')<=9,变量result记录转换后的整数,result = result*10+s.charAt(i) - '0';循环字符串,直到字符不为数字时结束循环;
(4)当整数溢出时,即result*flag>Integer.MAX_VALUE时,返回Integer.MAX_VALUE;result*flag<Integer.MIN_VALUE时,返回Integer.MIN_VALUE。
public class Solution { public int myAtoi(String str) { String s = str.trim(); if(s.length() == 0){ return 0; } int flag = 1; int result = 0; for(int i=0;i<s.length();i++){ if(i == 0){ if(s.charAt(0) == '+'){ flag = 1; }else if(s.charAt(0) == '-'){ flag = -1; }else if((s.charAt(0) - '0')>=0 && (s.charAt(0) - '0')<=9){ result = s.charAt(0) - '0'; }else{ return 0; } }else if((s.charAt(i) - '0')<0 || (s.charAt(i) - '0')>9){ break; }else{ if(Integer.MAX_VALUE/10 < result || Integer.MAX_VALUE/10 == result && Integer.MAX_VALUE %10 < (s.charAt(i)-'0')) return flag == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE; result = (result*10)+(s.charAt(i)-'0'); } } return result*flag; }}
- 8.String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8.String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 解决HTML嵌入Android项目乱码问题
- 大话CTF比赛之一
- 查看Android应用包名、Activity的几个方法
- spring mvc 配置详解
- 爬虫实战:学者网(二)
- 8. String to Integer (atoi)
- 访问Webroot下的资源文件
- Java中获取键盘输入值的三种方法
- CCF 历年真题之数字排序(_1503_2_NumericalSorting.java )参考答案
- hihoCoder #1318 : 非法二进制数 (动态规划)
- HTML链接标签 图片标签
- android 双击退出开发
- jstack简单使用,定位死循环、线程阻塞、死锁等问题
- Appium 新手学 appium-Appium for Windows 说明 (中文翻译)