11

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?

4 Answers 4

11
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
10
  • BigInteger has comparable methods if you outgrow long. Mar 28, 2012 at 21:24
  • 2
    This is incorrect. Due to the properties of the floating point arithmetic when x=10^n log(x) may be slightly smaller than n. When this happens your function returns 10^n-1 instead of 10^(n+1)-1. For example in double precision arithmetic x=1000 gives 999 instead of 9999 because log(1000) = 2.99999999999999955591e+00. Mar 28, 2012 at 21:46
  • ahhh .... picky ! [but correct]. I fixed to handle this... @adam, why just just suggest/provide the fix yourself ?? Mar 28, 2012 at 23:12
  • @CharlesBretana Yeah, this should fix it. Mar 28, 2012 at 23:15
  • 1
    @CharlesBretana I haven't edited the post, because I think it isn't very pretty to employ floating point to solve this in the first place. The fix with 1e-6 makes it even uglier. Mar 28, 2012 at 23:23
11
long maxNumber = long.Parse(new String('9', ItemNo.ToString().Length));
1
  • 1
    Like your answer better than accepted one. Why bother with FPU when CPU can do. More predictable than floating point, less testing headache. Helps to save some electricity as well
    – user215054
    Mar 29, 2012 at 2:36
5

Try this:

int v = 1;
do {
    v = v * 10;
} while (v <= number);
return v - 1;
1
int numDigits = (int)Math.Ceiling(Math.Log10(number));
int result = (int)(Math.Pow(10, numDigits) - 1)

I don't have a compiler available at the moment, so some additional string/double conversions may need to happen here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.