# Integer to Base 3 Number in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

Suppose we have a number n, we have to find the base 3 equivalent of this number as string.

So, if the input is like 17, then the output will be 122.

To solve this, we will follow these steps −

• if n<0:
• sign := -1
• otherwise sign := blank string
• n := |n|
• if n <3, then
• return n as string
• s := blank string
• while n is not same as 0, do
• s := string of (n mod 3) concatenate s
• n := quotient of (n / 3)
• return sign concatenate s

Let us see the following implementation to get better understanding −

## Example

Live Demo

class Solution:
def solve(self, n):
sign = '-' if n<0 else ''
n = abs(n)
if n < 3:
return str(n)
s = ''
while n != 0:
s = str(n%3) + s
n = n//3
return sign+s
ob = Solution()
print(ob.solve(17))

## Input

17

## Output

122