LintCode:转换字符串到整数
来源:互联网 发布:scratch创意编程 pdf 编辑:程序博客网 时间:2024/06/05 15:07
1.题目描述
实现atoi这个函数,将一个字符串转换为整数。如果没有合法的整数,返回0。如果整数超出了32位整数的范围,返回INT_MAX(2147483647)如果是正整数,或者INT_MIN(-2147483648)如果是负整数。关于合法整数的判断,主要是看字符串前面的一串数字,如:
10,,,,,233,返回10
,,,,,,10,不合法,返回0
2.解题思路和代码
public class Solution { /** * @param str: A string * @return An integer */ public int atoi(String str) {if (str == null || str.length() < 1)return 0;str = str.trim();char flag = 0;int i = 0;if (str.charAt(0) == '-') {flag = '-';i++;} else if (str.charAt(0) == '+') {flag = '+';i++;}double result = 0;while (str.length() > i && str.charAt(i) >= '0' && str.charAt(i) <= '9') {result = result * 10 + (str.charAt(i) - '0');i++;}if (flag == '-')result = -result;if (result > Integer.MAX_VALUE)return Integer.MAX_VALUE;if (result < Integer.MIN_VALUE)return Integer.MIN_VALUE;return (int) result;}}
阅读全文
0 0
- lintcode-转换字符串到整数
- lintcode,转换字符串到整数
- Lintcode 转换字符串到整数
- lintcode -- 转换字符串到整数
- LintCode:转换字符串到整数
- lintcode 转换字符串到整数
- 转换字符串到整数——LintCode
- lintcode之转换字符串到整数
- LintCode 54- 转换字符串到整数
- LintCode 54 转换字符串到整数
- [LintCode]54.转换字符串到整数
- LINTCODE——转换字符串到整数
- LintCode-剑指Offer-(54)转换字符串到整数
- 转换字符串到整数
- 转换字符串到整数
- 转换字符串到整数
- 转换字符串到整数
- Miscellaneous | 转换字符串到整数
- 【mybatis】--mapper代理实现dao
- RAID阵列实验
- JavaScript基础(改变html元素内容)
- fzu 2216 The Longest Straight
- 捕捉桌面上的窗口信息
- LintCode:转换字符串到整数
- git入门大全
- 小时到分钟
- 路径寻找问题
- 复习1
- Linux 安装 oh my zsh
- redis哨兵、集群
- 对 TCP 建立连接需要 3 次握手的理解
- NuttX 入门笔记2 STM32F103C8T6(STM32f103-minimum) 点亮led