Given a number N and its base b, convert it to decimal. The base of number can be anything such that all digits can be represented using 0 to 9 and A to Z. Value of A is 10, value of B is 11 and so on.
Example 1:
Input: b = 2, N = 1100
Output: 12
Explaination: It is a binary number whose 
decimal equivalent is 12.
Example 2:
Input: b = 16, N = A
Output: 10
Explaination: It's a hexadecimal number whose 
decimal equivalent is 10.
Your Task:
You do not need to read input or print anything. Your task is to complete the function decimalEquivalent() which takes N and b as input parameters and returns their decimal equivalent. Otherwise return -1 if N is not possible.
Expected Time Complexity: O(|N|)   [|N| means the length of the number N]
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ b ≤ 16
1 ≤ N < decimal equivalent 10^{9}

Source: geeksforgeeks | Difficulty: EASY
Tags: Mathematics

Starter code: #User function Template for python3



class Solution:

    def decimalEquivalent(self, N, b):

        # code here

Solutions:
class Solution:

	def decimalEquivalent(self, N, b):
		num = '0123456789'
		for i in N:
			if i in num and int(i) >= b:
				return -1
		return int(N, b)


class Solution:

	def decimalEquivalent(self, N, b):
		try:
			ans = int(N, b)
			return ans
		except:
			return -1


class Solution:

	def decimalEquivalent(self, N, b):
		try:
			x = int(str(N), base=b)
		except:
			return -1
		else:
			return x
if __name__ == '__main__':
	t = int(input())
	for _ in range(t):
		b = int(input())
		N = input()
		ob = Solution()
		print(ob.decimalEquivalent(N, b))


class Solution:

	def decimalEquivalent(self, N, b):
		s = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'A': 10, 'B': 11, 'C': 12, 'D': 13, 'E': 14, 'F': 15}
		d = len(N) - 1
		c = 0
		for i in N:
			if s[i] >= b:
				return -1
			c += b ** d * s[i]
			d -= 1
		return c
if __name__ == '__main__':
	t = int(input())
	for _ in range(t):
		b = int(input())
		N = input()
		ob = Solution()
		print(ob.decimalEquivalent(N, b))


class Solution:

	def decimalEquivalent(self, N, b):
		base = b
		no = N
		decimalNo = 0
		power = 1
		hexaDict = {'A': 10, 'B': 11, 'C': 12, 'D': 13, 'E': 14, 'F': 15}
		for c in no[::-1]:
			if c.isdigit():
				if int(c) >= b:
					return -1
				decimalNo += power * int(c)
			else:
				if hexaDict[c] >= b:
					return -1
				decimalNo += power * hexaDict[c]
			power = power * base
		return decimalNo


class Solution:

	def decimalEquivalent(self, N, b):
		sum = 0
		for i in range(0, len(N)):
			p = 0
			if N[i] == 'A':
				p = 10
			elif N[i] == 'B':
				p = 11
			elif N[i] == 'C':
				p = 12
			elif N[i] == 'D':
				p = 13
			elif N[i] == 'E':
				p = 14
			elif N[i] == 'F':
				p = 15
			else:
				p = int(N[i])
			if p > b:
				sum = -1
				break
			else:
				sum = sum * b + p
		return sum