Search code examples
c#mathnumbersnumber-formatting

Get min and max integer value containing X number of digits


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 = 9
  • x = 2: Min = 10, Max = 99
  • x = 3: Min = 100, Max = 999
  • x = 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.");
    }
}

Solution

  • Fox any x>1, the min value would be 10x-1. E.g.:

    • If x = 2, min=102-1 = 101 = 10
    • If x = 3, min=103-1 = 102 = 100
    • If x = 4, min=104-1 = 103 = 1000

    For x=1, since it's the only value that is not a one followed by a series of zeroes, you'll need special treatment.

    public static int MinIntWithXDigits(this int x)
    {
        if (x == 0) 
        {
            throw new ArgumentException(nameof(x), "An integer cannot contain zero digits.");
        }
    
        if (x == 1) {
            return 0;
        }
    
        try
        {
            return Convert.ToInt32(Math.Pow(10, x - 1));
        }
        catch 
        {
            throw new InvalidOperationException($"A number with {x} digits cannot be represented as an integer.");
        }
    }
    

    Side note:
    If the result were restricted to positive integers instead of non-negative integers, the smallest integer with one digit would be 1, and the general formula would have applied for this case too.