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