Skip to content
Programming101
Programming101

Learn everything about programming

  • Home
  • CS Subjects
    • IoT – Internet of Things
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
Programming101
Programming101

Learn everything about programming

Leetcode Base 7 problem solution

YASH PAL, 31 July 2024

In this Leetcode Base 7 problem solution Given an integer num, return a string of its base 7 representation.

Leetcode Base 7 problem solution

Problem solution in Python.

class Solution:
    def convertToBase7(self, num: int) -> str:
        if num==0:
            return "0"
        s='';ms=0
        if(num<0):
            num=-num
            ms+=1
        while(num>0):
            s+=str(num%7)
            num//=7
        s=s[::-1]
        return s if ms==0 else '-'+s

Problem solution in Java.

class Solution {
    public String convertToBase7(int num) {
        if (num == 0) {
            return "0";
        }
        String res = "";
        boolean isNegative = num < 0;
        long abs = Math.abs(num);
        while (abs > 0) {
            long rem = abs % 7;
            res = rem + res;
            abs /= 7;
        }
        if (isNegative) {
            res = "-" + res;
        }
        return res;
    }
}

Problem solution in C++.

class Solution {
public:
    string convertToBase7(int num) {
        string result ="";
        if(num==0) return to_string(num);
        string sign = "";
        if(num<0){
            sign = "-";
            num = -num;
        }
        while(num){
            result= to_string(num%7) + result;
            num /=7;
        }
        return sign + result;
    }
};

coding problems

Post navigation

Previous post
Next post
  • How AI Is Revolutionizing Personalized Learning in Schools
  • GTA 5 is the Game of the Year for 2024 and 2025
  • Hackerrank Day 5 loops 30 days of code solution
  • Hackerrank Day 6 Lets Review 30 days of code solution
  • Hackerrank Day 14 scope 30 days of code solution
©2025 Programming101 | WordPress Theme by SuperbThemes