New update is available. Click here to update.

Last Updated: 21 Feb, 2021

Difficulty: Easy

```
1. ‘N’ contains only digits ‘0’ to ‘9’ and English letters ‘A’ to ‘F’.
2. Decimal equivalent of 0 is 0, 1 is 1, . . .9 is 9, A is 10, B is 11, . . . F is 15.
```

```
The first line of input contains an integer 'T' representing the number of test cases.
The first line of each test case contains a string ‘N’ and an integer ‘Base’ separated by a single space.
```

```
For each test case, print the ‘N’ in base 10. If it’s impossible to convert ‘N’ to base 10 then print -1.
The output of each test case will be printed in a separate line.
```

```
1 <= T <= 5
1 <= decimal( N ) <= 10 ^ 9
1 <= B <= 16
Where ‘T’ is the number of test cases, decimal(N) is the decimal equivalent of ‘N’ and ‘B’ is the base of number ‘N’.
```

```
You do not need to print anything, it has already been taken care of. Just implement the given function.
```

The idea here is to use base conversion. We will simply divide the string into digits and then calculate the answer using the below formula.

num[ N – 1] * 1 + num[ N – 2 ] * base + num[N – 3] * (base) ^ 2 + . . . + num[ 0 ] * ( (base) ^ (N-1) )

Algorithm:

- Declare a variable to store the decimal equivalent of num, say ‘answer’, and initialize it with zero. Also, declare a variable ‘base’ to keep track of the base for current digit and initialize it with one. Here, ‘num’ is the given number.
- Run a loop from index = ‘N – 1’ to ‘index’ = 0. Here ‘N’ is the length of the number ‘N’.
- Convert num[ index ] to the equivalent digit in the decimal system, say ‘digit’. Example: ‘0’ becomes 0 and ‘B’ becomes 11.
- If ‘digit’ >= ‘B’, then return -1 as any digit cannot be greater or equal to the base of the number. Here, ‘B’ is given the base of the number.
- Add digit * base to the ‘answer’.
- Multiply ‘base’ with ‘B’ for the next iteration.
- Finally, return the ‘answer’.

SIMILAR PROBLEMS

Ninja And The LCM

Posted: 12 Apr, 2022

Difficulty: Easy

A Number Game

Posted: 23 Apr, 2022

Difficulty: Moderate

Pair Product Div by K

Posted: 15 May, 2022

Difficulty: Moderate

Pair Product Div by K

Posted: 15 May, 2022

Difficulty: Moderate

Merge Two Sorted Arrays Without Extra Space

Posted: 19 Nov, 2022

Difficulty: Moderate

Co-Prime

Posted: 14 Dec, 2022

Difficulty: Hard

Popular Interview Problems: