- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Base 3 to integer in Python
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
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
Advertisements