Given a string s representing a number in base 3 (consisting only of 0, 1, or 2), return its decimal integer equivalent.
Example 1
Input
s = “10”
Output
3
Example 2
Input
s = “21”
Output
7
Base 3 String to Integer Conversion Algorithm
Similarly to Binary String/Integer to Decimal, we need to sum the digit’s powers. Each digit should multiply by their corresponding power. The result is accumulated.
For example, “210” in base 3 equals the value:
2*pow(3,2)+1*pow(3,1)+0*pow(3,0)
O(N) time and O(1) space, the following is the C++ implementation of algorithm to convert Base 3 to Decimal value:
int base3(string s) {
int ans = 0;
for (auto &n: s) {
ans = ans * 3 + n - '0';
}
return ans;
}
Python code is similar:
class Solution:
def base3(self, s):
ans = 0
for i in s:
ans = ans * 3 + int(i)
return ans
–EOF (The Ultimate Computing & Technology Blog) —
199 wordsLast Post: Teaching Kids Programming - Enhanced Valid Parenthese String Algorithm using a Stack
Next Post: Breadth First Search Algorithm to Convert Level Order Binary Search Tree to Linked List