diff --git a/Java/string-to-integer-atoi.java b/Java/string-to-integer-atoi.java new file mode 100644 index 00000000..7c7cbcdc --- /dev/null +++ b/Java/string-to-integer-atoi.java @@ -0,0 +1,65 @@ +package com.bst.myexamples; + +/** + * Solution accepted on Leetcode with 7ms runtime and 39.2MB memory + * + * String to Integer (atoi) + * Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). + * Approach + * 1.Prepare String that is having only +- sign and number value + * Convert to BigInteger to compare value with 32bit signed Integer range and clamp if goes out of range + * return output with 0 if no string number found or non number value found before any number value + */ + +import java.math.*; +class StringToIntegerATOI { + + public static void main(String[] args){ + /* StringToIntegerATOI sta = new StringToIntegerATOI(); + System.out.println(sta.myAtoi("-20000000000000")); +*/ + + } + public int myAtoi(String s) { + + StringBuilder sb = new StringBuilder(); + + for(int i=0; i 0) + lvar = BigInteger.valueOf(Integer.MAX_VALUE); + else if(lvar.compareTo(BigInteger.valueOf(Integer.MIN_VALUE)) < 0) + lvar = BigInteger.valueOf(Integer.MIN_VALUE); + + return lvar.intValue(); + } +} \ No newline at end of file diff --git a/README.md b/README.md index 0e229327..a774967b 100644 --- a/README.md +++ b/README.md @@ -165,7 +165,7 @@ Check out ---> [Sample PR](https://github.com/codedecks-in/LeetCode-Solutions/pu | 859 | [Buddy Strings](https://leetcode.com/problems/buddy-strings/) | [Java](./Java/buddy-strings.java) | _O(n)_ | _O(1)_ | Easy | | | | 9 | [Palindrome Number](https://leetcode.com/problems/palindrome-number/) | [Java](./Java/palindrome-number.java) | _O(n)_ | _O(1)_ | Easy | | | | 767 | [Reorganize String](https://leetcode.com/problems/reorganize-string/) | [Python](./Python/reorganize-string.py) | _O(n)_ | _O(n)_ | Medium | | | - +| 8 | [String to Integer (atoi)](https://leetcode.com/problems/string-to-integer-atoi/) | [Java](./Java/string-to-integer-atoi.java) | _O(n)_ | _O(1)_ | Medium | | |
⬆️ Back to Top @@ -490,7 +490,7 @@ DISCLAIMER: This above mentioned resources have affiliate links, which means if | [Aysia](https://www.linkedin.com/in/aysiaelise/)
| USA | JavaScript | [GitHub](https://github.com/aysiae) | | [Poorvi Garg](https://github.com/POORVI111)
| India | C++ | [GitHub](https://github.com/POORVI111) | | [Lakshmanan Meiyappan](https://laxmena.com)
| India | C++ | [Website - Blog](https://laxmena.com)
[GitHub](https://github.com/laxmena)
[LinekdIn](https://www.linkedin.com/in/lakshmanan-meiyappan/) | - +| [Sachin_Upadhyay](https://github.com/sachsbu)
| India | Java | [GitHub](https://github.com/sachsbu) |
⬆️ Back to Top