Base 3 to integer in Python

PythonServer Side ProgrammingProgramming

Suppose we have a string s that is representing a number in base 3 (valid numbers 0, 1, or 2), we have to find its equivalent decimal integer.

So, if the input is like "10122", then the output will be 98.

To solve this, we will follow these steps −

• ans := 0

• for each digit c in s, do

• ans := 3 * ans + c

• return ans

Let us see the following implementation to get better understanding −

Example

Live Demo

class Solution:
def solve(self, s):
ans = 0
for c in map(int, s):
ans = 3 * ans + c
return ans
ob = Solution()
print(ob.solve("10122"))

Input

"10122"

Output

98
Updated on 02-Sep-2020 13:06:55