🚀 LeetCode #258 – Add Digits | Java Solution Another quick but insightful problem solved today! 💡 📌 Problem Statement Given an integer num, repeatedly add all its digits until the result becomes a single digit. 🔍 Example Input: 38 3 + 8 = 11 1 + 1 = 2 Output: 2 💻 Approach I Used (Iterative) Keep summing digits using % 10 and / 10 Repeat until the number becomes a single digit while (num >= 10) { int sum = 0; while (num != 0) { sum += num % 10; num = num / 10; } num = sum; } return num; 🧠 Key Learning Breaking numbers using modulo & division Looping until a condition is satisfied Understanding digit manipulation 📈 Small problems like this sharpen your thinking for bigger optimizations. Happy Coding 😊 #LeetCode #Java #DSA #ProblemSolving #CodingJourney #100DaysOfCode #Algorithms
Add Digits Java Solution LeetCode 258
More Relevant Posts
-
Day 70 of #100DaysOfLeetCode 💻✅ Solved #3136. Valid Word problem in Java. Approach: • Checked if the word length is at least 3 • Traversed each character in the string • Ensured all characters are either letters or digits • Checked for presence of at least one vowel • Checked for presence of at least one consonant • Returned true only if all conditions are satisfied Performance: ✓ Runtime: 1 ms (Beats 99.62% submissions) 🚀 ✓ Memory: 43.08 MB (Beats 93.16% submissions) Key Learning: ✓ Practiced string validation with multiple conditions ✓ Learned efficient use of built-in character functions ✓ Strengthened logic building for edge case handling Learning one problem every single day 🚀 #Java #LeetCode #DSA #Strings #ProblemSolving #CodingJourney #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Back with another update from my Java + DSA journey! Staying consistent and focusing on problem-solving mindset over memorizing solutions 💪 Today I worked on building logic step-by-step instead of jumping to code: • Max & Min of 3 Numbers (Using Methods) Created separate functions to find maximum and minimum Broke the problem into smaller comparisons Handled edge cases using >= and <= • Method Design & Parameters Learned how values flow from main() to methods Built clarity on pass by value and parameter usage Understood how methods act as reusable logic blocks • Avoiding Unnecessary Variables Optimized logic by reusing variables instead of creating extra ones Focused on writing cleaner and more efficient methods • Understanding Problem Statements (GFG) Realized that expected output matters more than function name Solved a tricky problem by identifying the real requirement: 👉 Print EVEN number first, then ODD using a function 💡 Key takeaway: Logic > Syntax Well-designed functions make logic clearer and code reusable. Small steps, stronger thinking 🧠🔥 Let’s keep improving every day 🚀 #Day3 #Java #DSA #ProblemSolving #Functions #LearningInPublic #Consistency #CodingJourney
To view or add a comment, sign in
-
-
🔥 Today's Learning Update — #Day51 Today’s concept: Why are Strings immutable in Java? 💡 What I understood In Java, once a String is created, it cannot be changed. If we try to modify it, a new String object is created instead. 💡 Why is it designed this way? 1️⃣ String Pool (Memory Efficiency) Multiple variables can point to the same String value without creating new objects. Since Strings are immutable, this is safe and saves memory. 2️⃣ Security Strings are used in things like file paths and database connections. If they were mutable, they could be changed during execution, which could cause serious issues. 3️⃣ HashCode Performance Since a String never changes, its hashCode can be cached. This makes it very efficient when used in structures like HashMap. 💡 Important observation When we “modify” a String, we are actually creating a new object, not changing the existing one. If we need frequent modifications, it’s better to use StringBuilder, which is mutable. 🧠 What I learned today Some design decisions in Java are not limitations — they are optimizations for performance, safety, and memory efficiency. #Java #CoreJava #String #Programming #SoftwareEngineering #ConsistencyCurve
To view or add a comment, sign in
-
-
𝗠𝗮𝘀𝘁𝗲𝗿𝗶𝗻𝗴 𝗝𝗮𝘃𝗮’𝘀 𝘃𝗮𝗿 Recently, I explored how Java introduced Local Variable Type Inference (var) in Java 10 and how it transformed the way developers write cleaner and more expressive code. Java has traditionally been known for its verbosity. With the introduction of var through Project Amber, the language took a major step toward modern programming practices—balancing conciseness with strong static typing. 𝗪𝗵𝗮𝘁 𝗜 𝗹𝗲𝗮𝗿𝗻𝗲𝗱: • var allows the compiler to infer types from initializers, reducing boilerplate without losing type safety. • It is not a keyword, but a reserved type name, ensuring backward compatibility. • Works only for local variables, not for fields, method parameters, or return types. • The inferred type is always static and compile-time resolved—no runtime overhead. • Powerful in handling non-denotable types, including anonymous classes and intersection types. Must be used carefully: • Avoid when the type is unclear from the initializer • Prefer when the initializer clearly reveals the type (e.g., constructors or factory methods) • Enhances readability only when the initializer clearly conveys the type. 𝗞𝗲𝘆 𝘁𝗮𝗸𝗲𝗮𝘄𝗮𝘆: var is not just about writing less code—it’s about writing clearer, more maintainable code when used correctly. The real skill lies in knowing when to use it and when not to. A special thanks to Syed Zabi Ulla sir at PW Institute of Innovation for their clear explanations and continuous guidance throughout this topic. #Java #Programming #SoftwareDevelopment #CleanCode #Java10 #Developers #LearningJourney
To view or add a comment, sign in
-
Solved LeetCode 17 – Letter Combinations of a Phone Number using backtracking in Java. Approach: Mapped each digit (2–9) to its corresponding characters using a simple array for O(1) access. Then used backtracking to build combinations digit by digit. For every digit: Pick each possible character Append → explore next digit → backtrack Key idea: Treat it like a tree of choices, where each level represents a digit and branches represent possible letters. Key learnings: Backtracking = build → explore → undo StringBuilder helps avoid unnecessary string creation Problems like this are about systematic exploration of choices Time Complexity: O(4^n * n) Space Complexity: O(n) recursion stack + output Consistent DSA practice is strengthening pattern recognition day by day. #Java #DSA #Backtracking #LeetCode #CodingInterview #SoftwareEngineering
To view or add a comment, sign in
-
-
Day 98 - LeetCode Journey Solved LeetCode 20: Valid Parentheses in Java ✅ A classic stack problem that looks simple but tests your attention to detail. The idea is straightforward: Push opening brackets into stack and match them correctly when a closing bracket appears. If anything mismatches → invalid. Clean logic, zero confusion 💡 Key takeaways: • Stack fundamentals • Matching pairs efficiently • Handling edge cases (empty stack, wrong order) • Writing clean conditional logic ✅ All test cases passed ⚡ O(n) time and O(n) space Sometimes basics like this are the real building blocks of strong DSA 🔥 #LeetCode #DSA #Java #Stack #ProblemSolving #CodingJourney #InterviewPrep #Consistency #100DaysOfCode
To view or add a comment, sign in
-
-
Day 94 - LeetCode Journey Solved LeetCode 35: Search Insert Position in Java ✅ Classic Binary Search problem that tests your fundamentals. Instead of just finding the element, the twist is to return the correct insert position if it’s not present. The key idea is simple: keep narrowing the search space and finally return low, which represents the right position. Clean logic, high impact 💡 Key takeaways: • Strong grip on Binary Search fundamentals • Understanding search space boundaries • Returning correct insertion index • Writing efficient O(log n) solutions ✅ All test cases passed ⚡ O(log n) time and O(1) space Mastering basics like Binary Search is what builds real problem-solving strength 🔥 #LeetCode #DSA #Java #BinarySearch #ProblemSolving #CodingJourney #InterviewPrep #Consistency #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Mastering Java Through LeetCode 🧠 Day 21 of My DSA Journey 📌 Problem Solved: Q.1657 – Determine if Two Strings Are Close 💡 Problem Insight: At first glance, this problem looks like a simple string comparison… But it actually tests your understanding of patterns, hashing, and transformations. We are allowed to: ✔ Swap characters (change order) ✔ Transform characters (swap frequencies) 🧠 Key Learning: Two strings are "close" if: ✅ They have the same set of characters ✅ Their frequency distribution matches (order doesn’t matter) 👉 That means: Order is irrelevant Only character presence + frequency pattern matters 🔍 Approach I Used: 1️⃣ Checked if lengths are equal 2️⃣ Counted frequency using arrays 3️⃣ Verified both strings have same unique characters 4️⃣ Sorted frequency arrays and compared ⚡ Example: word1 = "cabbba" word2 = "abbccc" ✔ Same characters → {a, b, c} ✔ Frequencies match after sorting → [1,2,3] 👉 Result: true Tech Stack: Java Concepts Covered: Hashing | Arrays | Frequency Count Takeaway: This problem taught me how to: Think beyond direct comparison Focus on data patterns instead of structure Consistency + Practice = Growth #LeetCode #DSA #Java #CodingJourney #100DaysOfCode #ProblemSolving #Developers #SoftwareEngineer #Learning #Growth #CDAC #PlacementPreparation #Tech
To view or add a comment, sign in
-
-
Day 75 of #100DaysOfLeetCode 💻✅ Solved #278. First Bad Version problem in Java. Approach: • Used Binary Search to minimize API calls • Narrowed search space using isBadVersion(mid) • Moved left/right pointers based on condition • Final position gives the first bad version Performance: ✓ Runtime: 16 ms (Beats 10.29% submissions) ✓ Memory: 42.16 MB (Beats 42.59% submissions) Key Learning: ✓ Practiced Binary Search with API-based problems ✓ Improved optimization by reducing unnecessary calls ✓ Strengthened problem-solving using monotonic conditions Learning one problem every single day 🚀 #Java #LeetCode #DSA #BinarySearch #ProblemSolving #CodingJourney #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 DSA in Java – Day 88 ✅ Today’s problem was all about finding the minimum distance between three equal elements in an array — and it really tested my ability to optimize brute force logic 💡 🔍 Approach I used: • Applied 3 nested loops to check all possible triplets • Optimized by skipping unnecessary comparisons using continue • Used break to stop early once a valid third element is found • Focused on minimizing (k - i) instead of full formula 💡 Key Insight: Instead of directly calculating the full distance, I realized that: 👉 Distance = 2 × (k - i) So minimizing (k - i) automatically gives the minimum distance 🚀 📈 What I learned today: • Even brute force can be improved with small optimizations • Early stopping (break) can reduce unnecessary iterations • Observing patterns in formulas helps simplify problems Some days are about solving fast, and some days are about thinking smarter — today was both 💯 Let’s keep growing consistently 💪 #DSAinJava #LeetCode #ProblemSolving #Java #CodingJourney #Consistency #100DaysOfCode
To view or add a comment, sign in
-
More from this author
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