Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the maximum number of a particular length

I have a number, for example 1234567897865; how do I max it out and create 99999999999999 ?

I did this this way:

        int len = ItemNo.ToString().Length;
        String maxNumString = "";

        for (int i = 0; i < len; i++)
        {
            maxNumString += "9";
        }

        long maxNumber = long.Parse(maxNumString);

what would be the better, proper and shorter way to approach this task?

like image 483
Andrew Avatar asked Mar 28 '12 21:03

Andrew


1 Answers

var x = 1234567897865;  
return Math.Pow(10, Math.Ceiling(Math.Log10(x+1e-6))) - 1;

To expand on comments below, if this problem was expressed in hex or binary, it could be done very simply using shift operators

i.e., "I have a number, in hex,, for example 3A67FD5C; how do I max it out and create FFFFFFFF?"

I'd have to play with this to make sure it works exactly, but it would be something like this:

var x = 0x3A67FD5C;  
var p = 0;
while((x=x>>1)>0) p++;          // count how many binary values are in the number
  return (1L << 4*(1+p/4)) - 1; // using left shift, generate 2 to 
                                // that power and subtract one
like image 156
Charles Bretana Avatar answered Nov 15 '22 12:11

Charles Bretana