Leetcode Practice - 8. String to Integer (atoi) The problem is solved using JAVA. Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer. The algorithm for myAtoi(string s) is as follows: ✔ Whitespace: Ignore any leading whitespace (" "). ✔ Signedness: Determine the sign by checking if the next character is '-' or '+', assuming positivity if neither present. ✔ Conversion: Read the integer by skipping leading zeros until a non-digit character is encountered or the end of the string is reached. If no digits were read, then the result is 0. ✔ Rounding: If the integer is out of the 32-bit signed integer range [-231, 231 - 1], then round the integer to remain in the range. Specifically, integers less than -231 should be rounded to -231, and integers greater than 231 - 1 should be rounded to 231 - 1. Return the integer as the final result. Example 1: Input: s = "42" Output: 42 Explanation: The underlined characters are what is read in and the caret is the current reader position. Step 1: "42" (no characters read because there is no leading whitespace) ^ Step 2: "42" (no characters read because there is neither a '-' nor '+') ^ Step 3: "42" ("42" is read in) #LeetCode #Java #StringHandling #CodingPractice #ProblemSolving #DSA #DeveloperJourney #TechLearning
Convert String to 32-bit Signed Integer in Java
More Relevant Posts
-
Leetcode Practice - 16. 3Sum Closest The problem is solved using JAVA Given an integer array nums of length n and an integer target, find three integers at distinct indices in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution. Example 1: Input: nums = [-1,2,1,-4], target = 1 Output: 2 Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). Example 2: Input: nums = [0,0,0], target = 1 Output: 0 Explanation: The sum that is closest to the target is 0. (0 + 0 + 0 = 0). Constraints: 3 <= nums.length <= 500 -1000 <= nums[i] <= 1000 -104 <= target <= 104 #LeetCode #Java #CodingPractice #ProblemSolving #DSA #Array #DeveloperJourney #TechLearning
To view or add a comment, sign in
-
-
Leetcode Practice - 15. 3Sum The problem is solved using JAVA. Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets. Example 1: Input: nums = [-1,0,1,2,-1,-4] Output: [[-1,-1,2],[-1,0,1]] Explanation: nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0. nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0. nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0. The distinct triplets are [-1,0,1] and [-1,-1,2]. Notice that the order of the output and the order of the triplets does not matter. Example 2: Input: nums = [0,1,1] Output: [] Explanation: The only possible triplet does not sum up to 0. Example 3: Input: nums = [0,0,0] Output: [[0,0,0]] Explanation: The only possible triplet sums up to 0. Constraints: 3 <= nums.length <= 3000 -105 <= nums[i] <= 105 #LeetCode #Java #CodingPractice #ProblemSolving #DSA #Array #DeveloperJourney #TechLearning
To view or add a comment, sign in
-
-
💻 String vs StringBuffer vs StringBuilder in Java – Know the Difference! In Java, handling text data is very common. Let’s understand the three important classes: 🔹 1. String ✔ Immutable (cannot be changed once created) ✔ Any modification creates a new object ✔ Safe and widely used Example: "String s = "Hello";" "s = s + " World"; // creates new object" --- 🔹 2. StringBuffer ✔ Mutable (can be changed) ✔ Thread-safe (synchronized) ✔ Slightly slower due to synchronization Example: "StringBuffer sb = new StringBuffer("Hello");" "sb.append(" World");" --- 🔹 3. StringBuilder ✔ Mutable (can be changed) ✔ Not thread-safe ✔ Faster than StringBuffer Example: "StringBuilder sb = new StringBuilder("Hello");" "sb.append(" World");" --- 💡 Key Difference: String = Immutable StringBuffer = Mutable + Thread-safe StringBuilder = Mutable + Faster 🚀 Use String for simple tasks, StringBuffer for multi-threading, and StringBuilder for better performance in single-threaded applications. #FortuneCloudTechnology #Java #Programming #String #JavaBasics #Coding #Developers #Learning
To view or add a comment, sign in
-
Day 11/100 – Java Practice Challenge 🚀 Continuing my #100DaysOfCode journey with another important Java concept. 🔹 Topic Covered: Compile-time vs Runtime Polymorphism 💻 Practice Code: 🔸 Compile-time Polymorphism (Method Overloading) class Calculator { int add(int a, int b) { return a + b; } int add(int a, int b, int c) { return a + b + c; } } 🔸 Runtime Polymorphism (Method Overriding) class Animal { void sound() { System.out.println("Animal sound"); } } class Cat extends Animal { @Override void sound() { System.out.println("Cat meows"); } } public class Main { public static void main(String[] args) { // Compile-time Calculator c = new Calculator(); System.out.println(c.add(10, 20)); System.out.println(c.add(10, 20, 30)); // Runtime Animal a = new Cat(); a.sound(); } } 📌 Key Learnings: ✔️ Compile-time → method decided at compile time ✔️ Runtime → method decided at runtime ✔️ Overloading vs Overriding difference 🎯 Focus: Understanding how Java resolves method calls 🔥 Interview Insight: Difference between compile-time and runtime polymorphism is one of the most frequently asked Java interview questions. #Java #100DaysOfCode #MethodOverloading #MethodOverriding #Polymorphism #JavaDeveloper #Programming #LearningInPublic
To view or add a comment, sign in
-
Day 43-Understanding Runtime Polymorphism in Java If compile-time polymorphism is about decisions made early, runtime polymorphism is where things get interesting — decisions are made while the program is running. What is Runtime Polymorphism? Runtime polymorphism is the ability of a program to decide which method to execute at runtime based on the object. It is achieved using method overriding. 🔹 Simple Idea: Same method name, same parameters… but different behavior depending on the object. 🔹 Example: class Card { void swipe() { System.out.println("Please wait..."); } } class CreditCard extends Card { void swipe() { System.out.println("Payment via Credit Card"); } } class DebitCard extends Card { void swipe() { System.out.println("Payment via Debit Card"); } } public class Main { public static void main(String[] args) { Card c; c = new CreditCard(); c.swipe(); // Credit Card method c = new DebitCard(); c.swipe(); // Debit Card method } } 🔹 What’s happening here? - The reference type is Card - But the object changes (CreditCard / DebitCard) - JVM decides which method to call at runtime 🔹 Key Points: ✔ Happens at runtime (execution time) ✔ Achieved using method overriding ✔ Also called Dynamic Binding / Late Binding ✔ JVM decides method execution based on actual object This is what makes Java powerful and flexible in real-world applications. #Java #OOP #Polymorphism #CodingJourney #ProgrammingBasics
To view or add a comment, sign in
-
-
. 🚀 Day 2 — First & Last Index of Repeating Characters ✅ Problem Find the first and last occurrence index of each repeating character in a string. import java.util.*; import java.util.stream.*; class FirstLastIndexFinder { public static void main(String[] args) { String input = "Programming"; Map<Character, List<Integer>> map = IntStream.range(0, input.length()) .boxed() .collect(Collectors.groupingBy( i -> input.charAt(i), LinkedHashMap::new, Collectors.toList() )); map.entrySet().stream() .filter(entry -> entry.getValue().size() > 1) .forEach(entry -> { List<Integer> indexes = entry.getValue(); System.out.println( "Key: " + entry.getKey() + ", First Index: " + indexes.get(0) + ", Last Index: " + indexes.get(indexes.size() - 1) ); }); } } 💡 Explanation 👉 Step-by-step: Use IntStream.range() to iterate over indexes Group indexes by character using groupingBy() Use LinkedHashMap to maintain insertion order Filter characters that appear more than once Get: First index → indexes.get(0) Last index → indexes.get(size - 1) ✅ Output Key: r, First Index: 1, Last Index: 9 Key: g, First Index: 3, Last Index: 10 Key: m, First Index: 6, Last Index: 7 Happy Learning!!!
To view or add a comment, sign in
-
Today I realized why we should avoid using result+= c in Java. 👉 Every time we use + with String, a new object is created (because Strings are immutable). 👉 This leads to O(n²) time complexity in loops and impacts performance. Instead, we should use StringBuilder / StringBuffer for efficient string manipulation. Here are 🔟 practical string optimization techniques I noted: 🥇 1. Use StringBuilder instead of + ❌ Bad String result = ""; for(char c : arr){ result += c; } ✅ Good StringBuilder sb = new StringBuilder(); for(char c : arr){ sb.append(c); } return sb.toString(); 👉 Reason: Avoids creating new objects repeatedly 🥈 2. Use charAt() instead of toCharArray() (when possible) ❌ char[] arr = str.toCharArray(); ✅ for(int i = 0; i < str.length(); i++){ char c = str.charAt(i); } 👉 Saves extra memory 🥉 3. Use StringBuilder.reverse() ❌ Manual reverse ✅ new StringBuilder(str).reverse().toString(); 🏅 4. Use String.join() String res = String.join(",", a, b, c); 🎯 5. Use .equals() instead of == str1.equals(str2); 👉 == compares reference, not value 🧠 6. Use startsWith() / endsWith() str.startsWith("abc"); ⚡ 7. Use indexOf() for search str.indexOf("abc"); 🔥 8. Avoid split() inside loops String[] parts = str.split(","); 👉 split() uses regex → expensive 🧩 9. Use StringBuilder for insert/delete StringBuilder sb = new StringBuilder(str); sb.insert(i, "x"); 🚀 10. Use String.valueOf() String s = String.valueOf(num); 💡 Key takeaway: If you’re working with strings in loops → always think about immutability + performance #Java #BackendDevelopment #Coding #Performance #DataStructures #SoftwareEngineering
To view or add a comment, sign in
-
💡 Java Tip: One Method to Remember for Type Conversion We used to rely on: Integer.parseInt(), Long.parseLong(), Double.parseDouble() → for converting String to primitives String.valueOf() → for converting values to String It works—but it can get confusing when switching between primitives, wrapper classes, and even char ↔ String conversions. 🔑 Simple takeaway: You can simplify most conversions by remembering just one method: 👉 WrapperClass.valueOf() ✅ Converts String → Wrapper (Integer, Long, Double, etc.) ✅ Works well with primitives (via autoboxing/unboxing) ✅ Keeps your code more consistent and readable Example: Integer i = Integer.valueOf("10"); Double d = Double.valueOf("10.5"); String s = String.valueOf(100); 🧠 Personal learning: Instead of memorizing multiple parsing methods, focusing on valueOf() makes type conversion easier to reason about and reduces cognitive load while coding. #Java #CleanCode #ProgrammingTips #BackendDevelopment #SoftwareEngineering #Learning
To view or add a comment, sign in
-
Q. Can an Interface Extend a Class in Java? This is a common confusion among developers and even I revisited this concept deeply today. - The answer is NO, an interface cannot extend a class. - It can only extend another interface. But there is something interesting: - Even though an interface doesn’t extend Object, all public methods of the Object class are implicitly available inside every interface. Methods like: • toString() • hashCode() • equals() These are treated as abstractly redeclared in every interface. ⚡ Why does Java do this? - To support upcasting and polymorphism, ensuring that any object referenced via an interface can still access these fundamental methods. ❗ Important Rule: While you can declare these methods in an interface, you cannot provide default implementations for them. interface Alpha { default String toString() { // ❌ Compile time error return "Hello"; } } Reason? Because these methods already have implementations in the Object class. Since every class implicitly extends Object, allowing default implementations of these methods in interfaces would create ambiguity during method resolution. Therefore, Java does not allow interfaces to provide default implementations for Object methods. 📌 Interfaces don’t extend Object, but its public methods are implicitly available. However, default implementations for them are not allowed. #Java #OOP #InterviewPreparation #Programming #Developers #Learning #SoftwareEngineering
To view or add a comment, sign in
-
🚀 LeetCode #496 – Next Greater Element I | Java Solution Today’s problem was a great introduction to Stacks + HashMaps — a powerful combination for optimizing search problems 🔥 📌 Problem Summary Given two arrays nums1 and nums2 (where nums1 is a subset of nums2), find the next greater element for each element in nums1 from nums2. 👉 The next greater element is the first element to the right that is larger than the current number. 💡 Approach I Used (Optimized – O(n)) Traverse nums2 using a monotonic decreasing stack For each element: If current element > stack top → it's the "next greater" Store mapping in a HashMap Finally, build result for nums1 using the map 💻 Java Code Snippet int[] arr = new int[n1.length]; Stack<Integer> stk = new Stack<>(); HashMap<Integer,Integer> map = new HashMap<>(); for(int i = 0; i < n2.length; i++){ while(!stk.isEmpty() && n2[i] > stk.peek()){ map.put(stk.pop(), n2[i]); } stk.push(n2[i]); } for(int j = 0; j < n1.length; j++){ arr[j] = map.getOrDefault(n1[j], -1); } 🧠 Key Learning Understanding Monotonic Stack Reducing brute force O(n²) → O(n) Using HashMap for quick lookups 📊 Example nums1 = [4,1,2] nums2 = [1,3,4,2] Output = [-1,3,-1] 🔥 Why this problem matters? Frequently asked in interviews Builds foundation for problems like: Daily Temperatures Stock Span Next Greater Element II Happy Coding 😊 #LeetCode #Java #DSA #Stack #CodingJourney #ProblemSolving #100DaysOfCode #Algorithms
To view or add a comment, sign in
-
Explore related topics
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development