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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With