Exercise Beginner: Base of the number

Request:
You are given a string (less than 255 characters). Write a program that determines whether the given string is a number in some number system with a base not more than 16, and, if so, determine the base of the number system, otherwise print -1.

Solution
First we declare an array of strings which will hold all the possible values of digits that system numbers with base till 16 can have. Than we get the number to be analyzed from user. Being that in the request we have that the given string must not have more than 255 characters this is the first controll tha we make, if the string is larger than 255 characters we print the value -1, which means that we do not have a valid input and we return by ending the method execution. We declare an integer variable highestIndex intialized with the value -1 and a boolean variable isValidDigit. The highestIndex variable will store the value of the biggest valid base for the digits of the string taken in input, and the boolean variable isValidDigit will store true if the digit will be valid in the end of the execution of the inner loop and false if it will not be valid. If the digit will not be valid it means that all the number itself is not valid so we print -1 again and return to terminate the execution of main method. The example code bellow shows the solution.

Example code:

The result of the execution is shown in the fiugre 1 bellow.


Figure 1: Execution


(please report broken link in the comment)

Comments

Popular posts from this blog

Free host and domain

C++ Beginner: Lesson 3 - Simple calculator

C++ Beginner: Lesson 4 - Tic Tac Toe game