while (n > 1)

if ( x != x % n)

break;

else

n /= 10;

x is in the reange n to n*10.

Solved

Posted on 1998-06-08

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.

Any advice?

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.

Any advice?

4 Comments

while (n > 1)

if ( x != x % n)

break;

else

n /= 10;

x is in the reange n to n*10.

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

Please reject the above answer and accept my answer.

Thank you.

JESUS LOVES YOU - sganta

Title | # Comments | Views | Activity |
---|---|---|---|

Prototype for MessageDlg in Embacadero XE 2 | 2 | 31 | |

How do I add zip/compression functionality to a C++ (Windows and Linux) application? | 3 | 83 | |

White board coding practice | 3 | 61 | |

Eclipse IDE - Cannot copy/paste from console output | 8 | 62 |

Join the community of 500,000 technology professionals and ask your questions.

Connect with top rated Experts

**12** Experts available now in Live!