What would be the best way to generate the lowest and highest integer values which contain x number of digits?
For example:
x= 1: Min = 0, Max = 9x= 2: Min = 10, Max = 99x= 3: Min = 100, Max = 999x= 4: Min = 1000, Max = 9999
I feel like this should be a really easy thing to accomplish but I'm struggling to get my head around the math behind it.
Here's what I've got so far for generating the max value (based on this answer):
public static int MaxIntWithXDigits(this int x)
{
if (x == 0) throw new ArgumentException(nameof(x), "An integer cannot contain zero digits.");
try
{
return Convert.ToInt32(Math.Pow(10, x) -1);
}
catch
{
throw new InvalidOperationException($"A number with {x} digits cannot be represented as an integer.");
}
}
If anyone can help with generating the min value or suggest improvements on the code above I'd appreciate it.
Edit
I'm almost there - this seems to work for everything except when x = 1 (and min value expected as 0)
public static int MinIntWithXDigits(this int x)
{
if (x == 0) throw new ArgumentException(nameof(x), "An integer cannot contain zero digits.");
x -= 1;
try
{
return Convert.ToInt32(Math.Pow(10, x));
}
catch
{
throw new InvalidOperationException($"A number with {x} digits cannot be represented as an integer.");
}
}