Convert Base 3 String To Decimal Integer


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:

1
2
3
4
5
6
7
int base3(string s) {
    int ans = 0;
    for (auto &n: s) {
        ans = ans * 3 + n - '0';
    }
    return ans;
}
int base3(string s) {
    int ans = 0;
    for (auto &n: s) {
        ans = ans * 3 + n - '0';
    }
    return ans;
}

Python code is similar:

1
2
3
4
5
6
class Solution:
    def base3(self, s):
        ans = 0
        for i in s:
            ans = ans * 3 + int(i)
        return ans
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) —

GD Star Rating
loading...
216 words
Last 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

The Permanent URL is: Convert Base 3 String To Decimal Integer

Leave a Reply