views:

368

answers:

4
  1. Given an integer, write a program that converts the given number to a number (in base 10). Hint - The given number could be in any base, but the base is unknown.
+6  A: 

That can't be done; without knowing the source base the number is ambiguous. 10 in base n translates to n in base 10; there are infinite possibilities

Michael Mrozek
+1  A: 

It is easy to do, once you've got the base.

You can get a lower bound for the base, by finding the highest digit. Like in the number 175234 the base must be at least 8. However you can never find an upper bound: The number could be any base from 8 to infinity.

Instead you can print out the number it would be, given the first base was e.g. 8, 9 or 10. Then the user can decide what he/she thinks.

Thomas Ahle
+4  A: 

I'm assuming by 'unknown' you mean the algorithm needs to be able to handle any base? Otherwise it's just plain impossible.

So you're basically asking for function convert(number, base) = base10Number?

count = 0
total = 0
for each digit in number, from least significant to most significant
  total = total + digit * base^count
  count = count + 1

e.g. convert(355,8)

  • first loop: total = 0 + 5 * 8^0 = 5
  • second loop: total = 5 + 5 * 8^1 = 45
  • third loop: total = 45 + 3 * 8^2 = 237

Result = 237

Flynn1179
A: 

The problem statement states that the base of the given number is unknown. Thus to proceed one must need to assume a base for the number. It is practically safe to assume that the digit with the maximum value in the number denotes the maximum that can be accounted in the unknown base. This number, for example if stated as, 254, it can be assumed that the number system consists of digits 0, 1, 2, 3, 4, 5 - or base 6.

if(!(((ascii >= '0') && (ascii <= '9')) || ((ascii >= 'A') && (ascii <= 'Z')))) {
   printf("Illegal number, can have only digits (0-9) and letters (A-Z)");

Hope this helps.

Manav MN