String to Integer (atoi)
来源:互联网 发布:在淘宝上怎么买盗版书 编辑:程序博客网 时间:2024/05/16 16:01
public class Solution { public int myAtoi(String str) { if (str == null || str.length() == 0) { return 0; } str = str.trim(); boolean positive = true; int i = 0; if (str.charAt(i) == '+') { i++; } else if (str.charAt(i) == '-') { i++; positive = false; } long num = 0; for (; i < str.length(); i++) { char c = str.charAt(i); if (c < '0' || c > '9') { break; } if (positive){ num = num*10 + (c - '0'); if(num >= Integer.MAX_VALUE) { return Integer.MAX_VALUE; } } else { num = num*10 - (c - '0'); if (num <= Integer.MIN_VALUE) { return Integer.MIN_VALUE; } } } return (int)num; } // public int myAtoi(String str) { // // 1. null or empty string // if (str == null || str.length() == 0) { // return 0; // } // // 2. whitespaces // str = str.trim(); // // 3. +/- sign // boolean positive = true; // int i = 0; // if (str.charAt(i) == '+') { // i++; // } else if (str.charAt(i) == '-') { // positive = false; // i++; // } // double temp = 0.0; // for (; i < str.length(); i++) { // // 4. invalid character // if (str.charAt(i) > '9' || str.charAt(i) < '0') { // break; // } // int digit = str.charAt(i) - '0'; // // 5. handle min & max // if (positive) { // // 6. calculate real value // temp = temp*10 + digit; // if (temp > Integer.MAX_VALUE) { // return Integer.MAX_VALUE; // } // } else { // temp = temp*10 - digit; // if (temp < Integer.MIN_VALUE) { // return Integer.MIN_VALUE; // } // } // } // int result = (int) temp; // return result; // }}
0 0
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- string to integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer(atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- Palindrome Permutation
- 让孩子一生不后悔
- 教学引导师培训
- Eclipse中,No compiler is provided in this environment. Perhaps you are running on a JRE rather than a
- 搭建Android Studio2.1配HTC One M8做测试环境
- String to Integer (atoi)
- 第49课:Spark中的新解析引擎Catalyst源码Optimizer彻底详解.
- Google百分比布局支持库----让屏幕适配更简单
- 进程的概念&&进程的描述&&进程控制块(task_struct)
- 网页开发之表单标签中method的get/post
- java-抽象类和接口的作用
- 15个Java的报表工具简介
- java-数据类型-运算
- Find K Pairs with Smallest Sums