Check whether number is palindrome or not - Leet Code Solution
Problem Statement Determine whether an integer is a palindrome. An integer is a…
August 28, 2019
Implement atoi which converts a string to an integer.
Example 1:
Input: "42"
Output: 42
Example 2:
Input: " -42"
Output: -42
Example 3:
Input: "4193 with words"
Output: 4193
Example 4:
Input: "words and 987"
Output: 0
We need to keep in mind that header includes spaces + and - character only. And, then valid integers. Then, we need to parse integers untill found. If any other character found, it is neglected.
Two special conditions: if the result is out of range (integer overflow, positive), Integer’s max value is returned if number is negative and overflow happened, return max negative value of integer.
public class Q8_StringToInteger {
public int myAtoi(String str) {
int s = 0;
boolean neg = false;
boolean foundFirstValidInteger = false;
int l = str.length();
for (int i=0; i<l; i++) {
char c = str.charAt(i);
if (!foundFirstValidInteger) {
if (c == ' ') continue;
if (c == '+') {
foundFirstValidInteger = true;
continue;
}
if (c == '-') {
foundFirstValidInteger = true;
neg = true;
continue;
}
}
if (c >= '0' && c <= '9') {
foundFirstValidInteger = true;
int num = c - '0';
if (s > Integer.MAX_VALUE/10 || (s == Integer.MAX_VALUE/10 && num > 7)) {
if (neg) return Integer.MIN_VALUE;
return Integer.MAX_VALUE;
}
s = s*10 + num;
}
else if (!foundFirstValidInteger) {
return 0;
}
else {
if (neg) return -s;
return s;
}
}
if (neg) return -s;
return s;
}
}
" -42" -> -42
debug 2
"42" -> 42
debug 1
"4193 with words" -> 4193
"words and 987" -> 0
"-91283472332" -> -2147483648
debug 1
"3.14159" -> 3
debug 1
"+-2" -> 0
" -0012a42" -> -12
"2147483648" -> 2147483647
Problem Statement Determine whether an integer is a palindrome. An integer is a…
Problem Statement Roman numerals are represented by seven different symbols: I…
** Inversion There is an array(a) and two indexes i and j. Inversion is the…
Problem Statement Given a linked list, swap every two adjacent nodes and return…
A number consists of digits. Example: 843. Its a 3-digit number. Radix sort…
Problem Implement an algorithm to determine if a string has all the characters…
In this post, we will see some of the frequently used concepts/vocabulary in…
System design interview is pretty common these days, specially if you are having…
Introduction You are given an array of integers with size N, and a number K…
Graph Topological Sorting This is a well known problem in graph world…
Problem Statement Given a Binary tree, print out nodes in level order traversal…
Problem Statement Given an array nums of n integers and an integer target, are…