简体   繁体   中英

How to use the length of an integer variable as the termination condition in a for loop

I have a for loop such as:

for (int indexCount = 2, thirdNumber.ToString().Length!=1000; indexCount++)

I want the loop to terminate when there are 1000 digits in thirdNumber . How can I do this?

It's not possible to have an int with 1000 digits. The maximum int value is 2,147,483,647, which is only 10 digits. As far as I'm aware, there are no built-in data types that would represent a number with 1000 digits, or even 100 digits for that matter.

Edit: A BigInteger can hold an arbitrarily large number (thanks Bradley Uffner ). You'll need to add a reference to the System.Numerics assembly. If you use/are using that as your data type, your original comparison of thirdNumber.ToString()!=1000 would be a valid check to see if it is not 1000 digits.

You could also take a more numbers-based approach and compare the BigInteger being checked to the smallest thousand digit number, which is a 1 followed by 999 zeroes. I'm not sure which method would be faster with numbers of this size, though I'd suspect the comparison between two BigIntegers.

class Program
{
    static void Main(string[] args)
    {
        BigInteger minThousandDigits = BigInteger.Parse(new string('9', 999)) + 1;
        BigInteger thousandMoreDigits = BigInteger.Parse(new string('5', 1000));
        BigInteger notAThousandDigits = BigInteger.Parse(new string('9', 999));

        //Displays false
        Console.WriteLine($"Is the first number less than a thousand digits? {thousandMoreDigits < minThousandDigits}");

        //Displays true
        Console.WriteLine($"Is the second number less than a thousand digits? {notAThousandDigits < minThousandDigits}");

        Console.ReadLine();

    }
}

Use a do loop:

    int indexCount = 2;
    do 
    {
        // Whatever
        indexCount++;
    } while (thirdNumber.ToString().Length != 1000);

Note that the loop will always execute at least once in the above example. You can avoid this by using a break statement:

    int indexCount = 2;
    do 
    {
        if (thirdNumber.ToString().Length == 1000) break;
        // Whatever
        indexCount++;
    } while (true);

The above assumes that length will eventually be equal to 1000, otherwise you'll have an infinite loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM