🚀 Day 37 of #100DaysOfCode – LeetCode Problem #504: Base 7 💡 Problem Summary: Convert an integer into its Base 7 representation — without using any built-in conversion functions. 📘 Example: Input: num = 100 Output: "202" Input: num = -7 Output: "-10" 🧠 Intuition: Base conversion is all about repeated division and remainder operations. You divide the number by the base (in this case, 7) and record the remainder — those remainders form the digits of your result (in reverse order). 💻 Java Code: class Solution { public String convertToBase7(int num) { if (num == 0) return "0"; StringBuilder ans = new StringBuilder(); int temp = num; while (temp != 0) { ans.append(Math.abs(temp % 7)); temp /= 7; } ans.reverse(); if (num < 0) ans.insert(0, '-'); return ans.toString(); } } ⚙️ Complexity: Time: O(log₇(n)) Space: O(1) ✅ Result: Accepted (Runtime: 0 ms) 🎯 Key takeaway: Even simple math-based problems are a great reminder that fundamental concepts never go out of style — division, modulo, and a clear understanding of number systems go a long way in coding interviews.
Converting Integers to Base 7 in Java
More Relevant Posts
-
🧩 1️⃣ Mutable Strings Unlike regular String objects, which are immutable, Java provides two classes for mutable strings — StringBuffer and StringBuilder. 🔹 Mutable means you can change the content of the string without creating a new object. This makes them ideal for operations like concatenation, insertion, or deletion in loops or large text processing tasks. 🔸 StringBuffer – Thread-safe (synchronized), suitable for multi-threaded environments. 🔸 StringBuilder – Faster, non-synchronized, suitable for single-threaded programs. 👉 Mutable strings enhance performance when frequent modifications are needed. 🔒 2️⃣ Encapsulation Encapsulation is one of the core principles of Object-Oriented Programming (OOP). It means binding data (variables) and methods into a single unit — a class — and restricting direct access to the data. By making variables private and providing public getters and setters, we achieve data hiding and controlled access. This protects the internal state of objects and ensures that data can only be modified in a safe and predictable way. 💡 Encapsulation = Security + Modularity + Maintainability ⚙️ 3️⃣ Static Variables A static variable belongs to the class rather than to any specific object. This means all objects of that class share the same copy of the variable. Static members are used when a value should remain consistent across all instances — such as counters, configuration values, or constants. They are loaded into memory once when the class is first loaded, optimizing resource usage. 💡 Key Takeaways ✅ Mutable strings (StringBuffer, StringBuilder) allow efficient string modification. ✅ Encapsulation secures data and maintains class integrity. ✅ Static variables enable shared memory space and consistency across objects. 🎯 Reflection Today’s concepts emphasized how Java balances performance, security, and efficiency — from mutable strings improving speed to encapsulation ensuring clean data flow, and static variables optimizing memory. 🚀 #Java #Programming #Coding #LearningJourney #DailyLearning #RevisionDay #FullStackDevelopment #SoftwareEngineering #TAPAcademy #TechCommunity #JavaDeveloper #Encapsulation #StaticKeyword #MutableStrings #OOPsConcepts
To view or add a comment, sign in
-
-
💡 LeetCode 3110 – Score of a String 💡 Today, I solved LeetCode Problem #3110: Score of a String, a neat little challenge that emphasizes understanding of ASCII values and absolute differences in Java strings. 🔠✨ 🧩 Problem Overview: You’re given a string s. The score of the string is defined as the sum of the absolute differences between the ASCII values of consecutive characters. Return the total score. 👉 Example: Input → "hello" Output → 13 Explanation → |'e'-'h'| + |'l'-'e'| + |'l'-'l'| + |'o'-'l'| = 3 + 7 + 0 + 3 = 13 💡 Approach: 1️⃣ Initialize a variable sum to store the total score. 2️⃣ Traverse the string from index 1 to end. 3️⃣ For each pair of consecutive characters, find their ASCII difference using Math.abs(). 4️⃣ Add the difference to sum and return it. ⚙️ Complexity Analysis: ✅ Time Complexity: O(n) — Single traversal of the string. ✅ Space Complexity: O(1) — Constant extra space. ✨ Key Takeaways: Strengthened understanding of character encoding and ASCII values. Reinforced clean looping logic and mathematical precision in Java. A great example of how simplicity can elegantly solve a real problem. 🌱 Reflection: Even the smallest coding challenges help sharpen attention to detail — from understanding data types to leveraging built-in functions effectively. Consistency is what transforms learning into mastery. 🚀 #LeetCode #3110 #Java #StringManipulation #ASCII #ProblemSolving #DSA #CodingJourney #CleanCode #AlgorithmicThinking #ConsistencyIsKey
To view or add a comment, sign in
-
-
Understanding Method Overloading & Method Overriding in Java 💡 Both concepts seem similar — but they’re not! Here’s the difference 👇 🔹 Method Overloading (Compile-Time Polymorphism) ➡️ Same method name, different parameters ➡️ Happens within the same class ➡️ Resolved at compile time class Calculator { int add(int a, int b) { return a + b; } double add(double a, double b) { return a + b; } // Overloaded } 📘 Use when you want flexibility with inputs but same logic. 🔹 Method Overriding (Runtime Polymorphism) ➡️ Same method name & parameters ➡️ Happens in subclass ➡️ Resolved at runtime class Animal { void sound() { System.out.println("Animal sound"); } } class Dog extends Animal { @Override void sound() { System.out.println("Bark"); } } 📘 Use when a child class modifies parent behavior. 🔑 Key Takeaways ✅ Overloading → same method name, different parameters ✅ Overriding → same method signature, different behavior ✅ Overloading = Compile-time | Overriding = Runtime ✨ #Java #OOPs #MethodOverloading #MethodOverriding #JavaLearning
To view or add a comment, sign in
-
Tired of writing repetitive getters, constructors, equals(), hashCode(), and toString() methods? Record Classes, introduced in Java 16, offer a clean, immutable, and compact way to model data! 🚀 ⸻ 🧱 Before Records (Traditional Java Class) public class User { private final String name; private final int age; public User(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } @Override public String toString() { return "User[name=" + name + ", age=" + age + "]"; } } 😩 Lot of boilerplate just to hold data! ⸻ ⚡ With Record Classes (Java 16+) public record User(String name, int age) {} That’s it. Java automatically generates: • Constructor • Getters • equals() and hashCode() • toString() All while keeping the class immutable by default. ⸻ 🎯 Why Records Are Awesome • Perfect for DTOs, API responses, and simple data models • Built-in immutability • Far less boilerplate, far more clarity • Great performance and readability 👉 Stay with me for more new features of Java! #Java #Programming #CodeTips #Java16 #Records #CleanCode #Developers
To view or add a comment, sign in
-
💡5 Spring annotations that make your life easier but most devs never really use! Here are 5 Spring annotations that are underrated yet super powerful ✅@ConditionalOnProperty It's a spring boot annotation that allows you to turn beans on/off based on config properties. Perfect for feature toggle on environment specific beans Where is it used? ✔️Loading beans only in specific environment(dev, test, prod) ✔️Enabling/Disabling features dynamically by config ✔️To avoid unnecessary bean creation and save resource ✅@ConfigurationProperties This annotation allows you to bind external configuration(like application. properties or application.yml) directly to a Java class. Cleaner than multiple @Values Why use it? ✔️Avoids repetitive @Values injections. ✔️Makes configuration type-safe ✔️Supports nested objects and complex objects ✔️Perfect for grouping related configurations (like database, email, or API settings) ✅@EventListener This annotation allows a method to listen to application events without having to implement an old ApplicationListener interface. Why use it? ✔️Event driven made simple. ✔️Helps decouple components. ✔️Makes code cleaner avoiding boilerplate ApplicationListener classes implementation. ✔️Works with custom events and built-in spring events. ✅@Profile This annotation allows you to control which beans are loaded on the active environment. Why use it? ✔️Defines which bean to load in which environment. ✔️Avoid deploying dev/test beans to production. ✔️ Helps manage environment specific configurations cleanly ✅Value("#{…}") SpEL This annotation injects dynamic values using Spring Expression Language. It allows you to ✔️Evaluate mathematical expressions ✔️Call methods ✔️Access other beans or their properties ✔️Manipulate collections or arrays ✨ Pro Tip: Using these annotations wisely can make your Spring applications cleaner, more maintainable, and highly flexible. #Spring #SpringBoot #Annotations #JavaProgramming #DeveloperCommunity #Java #TechInsights
To view or add a comment, sign in
-
🚀 Day 39 of #100DaysOfCode – LeetCode Problem #917: Reverse Only Letters 💡 Problem Summary: Given a string s, reverse only the English letters while keeping all non-letter characters in their original positions. 📘 Examples: Input: s = "ab-cd" Output: "dc-ba" Input: s = "a-bC-dEf-ghIj" Output: "j-Ih-gfE-dCba" Input: s = "Test1ng-Leet=code-Q!" Output: "Qedo1ct-eeLg=ntse-T!" 🧠 Approach: Use two pointers: one starting from the beginning and one from the end. Move both pointers until they point to letters. Swap the letters and move inward. Skip over non-letter characters. 💻 Java Solution: class Solution { public String reverseOnlyLetters(String s) { char[] res = s.toCharArray(); int left = 0, right = res.length - 1; while (left < right) { if (!Character.isLetter(res[left])) { left++; } else if (!Character.isLetter(res[right])) { right--; } else { char temp = res[left]; res[left] = res[right]; res[right] = temp; left++; right--; } } return new String(res); } } ⚙️ Complexity: Time: O(n) Space: O(n) ✅ Result: Accepted (Runtime: 0 ms) 🎯 Key Takeaway: This problem highlights precision and attention to detail — even simple string manipulations can teach valuable lessons about pointer logic and conditional handling.
To view or add a comment, sign in
-
I solved LeetCode 42: Trapping Rain Water in Java, and it turned out to be one of those problems that looks straightforward at first but hides deep lessons in algorithm design and optimization. The problem asks you to calculate how much water can be trapped between bars of different heights after it rains. It sounds simple, but when you try to implement it, you realize how easily brute-force approaches break down. My initial solution used nested loops to check how much water could be trapped at every index. It worked but ran with O(n²) time complexity, which quickly became inefficient for large inputs. That is when I shifted toward precomputation. The key idea is to figure out how much water each bar can hold by knowing the tallest bar to its left and right. Once that information is known, the amount of trapped water at any position is simply the minimum of those two maximum heights minus the height of the bar itself. To make this efficient, I created two arrays: maxLeft[i] stores the tallest bar to the left of index i. maxRight[i] stores the tallest bar to the right of index i. This approach brought the time complexity down to O(n) while keeping the logic simple and elegant. This problem taught me that performance improvements often come from rethinking the way you process information. Precomputation, caching, and avoiding repetitive operations are not just algorithmic tricks. They are the same concepts that drive efficiency in backend engineering, database optimization, and system design. In many ways, this problem reflects real-world engineering. It is not about how fast you can write code, but how effectively you can anticipate what the system will need before it needs it. That mindset is what separates good developers from great ones. What is one problem that helped you truly understand the balance between simplicity and optimization? #Java #Programming #SoftwareDevelopment #ProblemSolving #Algorithms #Coding #DSA #LeetCode #Engineering #SystemDesign
To view or add a comment, sign in
-
-
🎯 𝐏𝐚𝐭𝐭𝐞𝐫𝐧 𝐌𝐚𝐭𝐜𝐡𝐢𝐧𝐠 𝐟𝐨𝐫 𝐢𝐧𝐬𝐭𝐚𝐧𝐜𝐞𝐨𝐟 — 𝐂𝐥𝐞𝐚𝐧, 𝐒𝐦𝐚𝐫𝐭 & 𝐌𝐞𝐦𝐨𝐫𝐲 𝐄𝐟𝐟𝐢𝐜𝐢𝐞𝐧𝐭 Let’s be honest — we all have written code like below👇 if (obj instanceof String) { String str = (String) obj; System.out.println(str.toUpperCase()); } Looks simple , but a bit cluttered — extra casting, redundant syntax, and more memory reads than needed. 💡 𝐄𝐧𝐭𝐞𝐫 𝐏𝐚𝐭𝐭𝐞𝐫𝐧 𝐌𝐚𝐭𝐜𝐡𝐢𝐧𝐠 𝐟𝐨𝐫 𝐢𝐧𝐬𝐭𝐚𝐧𝐜𝐞𝐨𝐟 Java 14+ introduced a more elegant approach: if (obj instanceof String str) { System.out.println(str.toUpperCase()); } ✅ No need for explicit casting ✅ Cleaner and safer — variable str is automatically scoped ✅ Slightly more memory-efficient — avoids redundant reference assignments ⚙️ 𝐖𝐡𝐲 𝐈𝐭 𝐌𝐚𝐭𝐭𝐞𝐫𝐬 Pattern Matching for instanceof: ✔️Reduces boilerplate — no need to write repetitive casts ✔️Improves readability — focuses on what the logic is, not how it’s written ✔️Enhances compiler checks — prevents accidental ClassCastExceptions ✔️Memory advantage: older style created redundant variable references; pattern matching uses optimized bytecode under the hood 🔍 Real-World Example: Before 👇 if (obj instanceof Employee) { Employee e = (Employee) obj; if (e.getSalary() > 100000) { System.out.println("High earner: " + e.getName()); } } After 🚀 if (obj instanceof Employee e && e.getSalary() > 100000) { System.out.println("High earner: " + e.getName()); } Now that’s clean Java! 🧹 #Java #JavaTips #CleanCode #CodeQuality #JavaDevelopers #Programming #SoftwareEngineering #BackendDevelopment #Java17 #CodingBestPractices
To view or add a comment, sign in
-
-
✨ Don’t Use the ELSE Keyword — Simplifying Logic and Improving Readability 💡 One of the most interesting rules from Object Calisthenics is: “Don’t use the ELSE keyword.” At first glance, it seems radical — after all, else is a fundamental part of most programming languages. But when we stop using it, we start writing more linear, readable, and intentional code. In Java, this principle pushes us to design methods that express decisions clearly, avoiding nested logic and long conditional chains. Instead of focusing on what happens otherwise, we focus on the main flow — and that changes everything. 🤔 Why avoid else? ❌ Nested complexity: Each else adds one more level of indentation, making it harder to follow the method’s logic. ❌ Blurry intent: When if and else blocks both contain logic, it becomes harder to see the “happy path.” ❌ Difficult evolution: As rules grow, new else if statements quickly create a tangle of conditions. 🚀 What improves when you remove it? ✨ Simpler flow: By handling edge cases early (using guard clauses), the main path remains clean and focused. ✨ Better readability: The method reads like a short story — straightforward, without mental jumps. ✨ More maintainable code: Fewer nested blocks mean fewer bugs and easier refactoring. #Java #CleanCode #ObjectCalisthenics #Refactoring #CodeQuality #SoftwareDesign #SpringBoot
To view or add a comment, sign in
-
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