Solved

# Algorithm

Posted on 1998-06-08
353 Views
What is the best algorithm to check a number is in which particular range of:
0 to 9
10 to 99
100 to 999
1000 to 9999
10000 to 99999
...rate at exponential of 10

E.g X = 555 is in the range of 100 - 999

I use a if-else-then to do the checking but its looks terribly ugly.

0
Question by:engllf

LVL 23

Accepted Solution

chensu earned 50 total points
ID: 1165459
Which is the best depends on the actual requirements. Here is an alternative. But you still need to check the value of n. You may use n as an index of an array.

#include <math.h>

.

if (X >= 0)
{
unsigned int n = X == 0 ? 0 : log10((double)X);
// 0 to 9, n = 0
// 10 to 99, n = 1
// 100 to 999, n = 2
// 1000 to 9999, n = 3
// ...
}
else
{
...
}

0

LVL 4

Expert Comment

ID: 1165460

I have simple and beautiful algorithm and solution for your problem.

ALGORITHM
1. Read the number into "n";
2. Store this number n as a string into test
i.e., test = string(n);
3. Get the length of the string into length
length = string_length(n);
4. Now
Range_From = power(10,length-1)
Range_To     = power(10,length)-1
5. End of the algorithm

/* Here the solution in C++ */

#include <iostream.h>
#include <string.h>
#include <math.h>

void main(void)
{
int n,len,ifrom,ito;
char *test;

cout << "Enter a number ";
cin >>n;

test = itoa(n); /* Converts integer to Ascii */
len = strlen(test);
ifrom = pow(10,len-1);
ito = pow(10,len)-1;
cout << "The number "<<n<<" is in the range from "<<ifrom<<" to "<<ito<<endl;
}

This  algorithm is tested and it works fine. If you are interested with my answer
Thank you.
JESUS LOVES YOU - sganta

0

LVL 22

Expert Comment

ID: 1165461
engllf, just so you know, while sganta's solution is pretty short and very slick, it is not very efficient.  If you are concerned about speed, you'll want to use chensu's solution.  But if you aren't concerned about speed, sganta's solution is pretty clear and simple.
0

## Featured Post

### Suggested Solutions

When writing generic code, using template meta-programming techniques, it is sometimes useful to know if a type is convertible to another type. A good example of when this might be is if you are writing diagnostic instrumentation for code to generatâ€¦
Written by John Humphreys C++ Threading and the POSIX Library This article will cover the basic information that you need to know in order to make use of the POSIX threading library available for C and C++ on UNIX and most Linux systems.   [sâ€¦
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.