Converting Integers to Base 7 in Java

🚀 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.

To view or add a comment, sign in

Explore content categories