【leetcode刷题笔记】String to Integer (atoi)

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.

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.



题解:思路很简单,就是要注意的细节很多:

  1. str中整数的前面可能有很多空格,要用str = str.trim(); 去掉,去掉之后还要判断str是否为空了,为空返回0;
  2. str中整数可能带有‘+‘或者‘-‘,也可以不带,带有负号的时候要单独处理;
  3. str中整数后面可能还有乱七八槽的非数字符号,直接忽略,所以在遍历过程中如果遇到这些符号,说明整数部分遍历结束,要推出循环。
  4. str转换出来的整数有可能大于Integer.MAX_VALUE,此时需要返回Integer.MAX_VALUE;也有可能小于Integer.MIN_VALUE,此时需要返回Integer.MIN_VALUE。

代码如下:

 1 public class Solution {
 2     public int atoi(String str) {
 3         if(str == null || str.length() == 0)
 4             return 0;
 5
 6         str = str.trim();
 7         if(str.length() == 0)
 8             return 0;
 9
10         int kepeler = 0;
11         boolean isNeg = false;
12         if(str.charAt(kepeler) == ‘-‘){
13             isNeg = true;
14             kepeler++;
15         }
16         else if(str.charAt(kepeler) == ‘+‘)
17             kepeler++;
18
19         long answer = 0;
20         for(;kepeler < str.length();kepeler++){
21             if(str.charAt(kepeler) < ‘0‘ || str.charAt(kepeler) > ‘9‘)
22                 break;
23             answer = answer*10+str.charAt(kepeler) - ‘0‘;
24         }
25         if(isNeg){
26             answer *= -1;
27             if(answer < Integer.MIN_VALUE)
28                 return Integer.MIN_VALUE;
29             return (int)answer;
30         }
31         else {
32             if(answer > Integer.MAX_VALUE)
33                 return Integer.MAX_VALUE;
34             return (int)answer;
35         }
36     }
37 }

【leetcode刷题笔记】String to Integer (atoi)

时间: 2024-12-19 00:34:28

【leetcode刷题笔记】String to Integer (atoi)的相关文章

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

题目String to Integer (atoi)(难度Medium) 大意是找出给定字串开头部分的整型数值,忽略开头的空格,注意符号,对超出Integer的数做取边界值处理. 方案1 1 class Solution { 2 fun myAtoi(str: String): Int { 3 val maxInt = "2147483647" 4 val maxIntS = "+2147483647" 5 val minIntS = "-21474836

【leetcode刷题笔记】Integer to Roman

Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999. 题解:基本的罗马字符和数字对应如下表所示: 罗马字符 数字 I 1 V 5 X 10 L 50 C 100 D 500 M 1000 每隔一个字符又可以与相邻的两个字符组成一个新的数,例如I可以和V和X组成IV和IX,这样又可以生成6个数字,如下表: 罗马字符 数字 IV 4 IX

【leetcode刷题笔记】Roman to Integer

Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999. 题解:转换的方法:从左往右扫描罗马字符,如果当前的字符对应的数字比上一个数字小,就直接加上这个数字:否则加上这个数字并且减去上一个数字的两倍,然后更新上一个数字.利用一个HashMap存放罗马字符和数字的对应. 罗马数字和阿拉伯数字的对应表格参见http://www.cnblogs.

【leetcode刷题笔记】Interleaving String

Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. For example,Given:s1 = "aabcc",s2 = "dbbca", When s3 = "aadbbcbcac", return true.When s3 = "aadbbbaccc", return false. 题解:DP问题. 用数组dp[i][

【leetcode刷题笔记】Scramble String

Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively. Below is one possible representation of s1 = "great": great / gr eat / \ / g r e at / a t To scramble the string, we may choose a

【leetcode刷题笔记】Restore IP Addresses

Given a string containing only digits, restore it by returning all possible valid IP address combinations. For example:Given "25525511135", return ["255.255.11.135", "255.255.111.35"]. (Order does not matter) 题解:深度优先搜索.用resul

【leetcode刷题笔记】Substring with Concatenation of All Words

You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters. For example, given:S: "b

【leetcode刷题笔记】N-Queens

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other. Given an integer n, return all distinct solutions to the n-queens puzzle. Each solution contains a distinct board configuration of

【leetcode刷题笔记】Minimum Window Substring

Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). For example,S = "ADOBECODEBANC"T = "ABC" Minimum window is "BANC". Note:If there is no such window i