问题描述

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.

原题链接:https://leetcode.com/problems/string-to-integer-atoi/

Analysis

public int myAtoi(String str) {
if(str == null || str.length() == 0){
return 0;
}
char[] chs = str.trim().toCharArray();
int isPositive = 1, index = 0;
if(chs[0] == '-'){
isPositive = -1;
index = 1;
}
if(chs[0] == '+'){
isPositive = 1;
index = 1;
}
long res = 0;
for(; index < chs.length; index++){
if(chs[index] < '0' || chs[index] > '9' ){
return (int)res;
}
res = res * 10 + isPositive * (chs[index] - '0');
if(res > Integer.MAX_VALUE){
return Integer.MAX_VALUE;
}
if(res < Integer.MIN_VALUE){
return Integer.MIN_VALUE;
}
}
return (int)res;
}

最新文章

  1. 如何一步一步用DDD设计一个电商网站(四)—— 把商品卖给用户
  2. hadoop配置远程客户端
  3. django view使用学习记录
  4. jQuery遍历 slice()方法
  5. oracle expdp和impdp使用例子
  6. 如何用VB获得Windows各类系统目录
  7. Spring xml中进行面向切面的配置
  8. 毕向东udp学习笔记3多线程聊天
  9. SolrCloud的介绍
  10. 江西财经大学第二届程序设计竞赛同步赛 H大时钟 (扩展欧几里得)
  11. Java_泛型
  12. vue this.$router.push和this.$route.path的区别
  13. 宽字符————_T、_TEXT、L、TEXT之间的区别
  14. 『计算机视觉』Mask-RCNN
  15. ASP.NET Identity系列01,揭开神秘面纱
  16. vue---设置缩进为4个空格
  17. HTTPS 通俗简介
  18. 清除 Exchange 2013/2016/2019 日志和ETL文件
  19. Gulp 有用的地址
  20. linux sed使用(转)

热门文章

  1. Graphviz--图形绘制工具
  2. 使用Ratpack与Spring Boot构建高性能JVM微服务
  3. python使用itchat库实现微信机器人
  4. python基础autopep8__python代码规范
  5. 集合-Table
  6. ES6知识整理(1)--let和const命令
  7. 从Xilinx FFT IP核到OFDM
  8. jquery实现登录加密的几种方法以及cookie存放加密/解密
  9. 安卓开发笔记(三十一):shape标签下子类根结点的具体使用
  10. 【STM32H7教程】第12章 STM32H7的HAL库框架设计学习