Problem of the Day
A new programming or logic puzzle every Mon-Fri

Int Overflow

Today's problem is a simple one but it will require a language which places restrictions on integer sizes such as C. The goal is to set an int to 1 and then double it until overflows. When the int overflows print out the number. Alternatively you can solve this by hand. Assume 32 bit signed integer.

Permalink: http://problemotd.com/problem/int-overflow/

Comments:

  • Anonymous - 9 years, 3 months ago

    C#

    class Program
    {
        static void Main(string[] args)
        {
            int i = 1;
    
            try
            {
                checked
                {
                    while (true)
                        i += i;
                }
            }
            catch (OverflowException) { }
    
            Console.WriteLine(i.ToString());
            Console.ReadKey();
        }
    }
    

    reply permalink

  • 17 minutes ago - 9 years, 3 months ago

    Javascript

    i=1;while(i<i<<1)i<<=1;alert(i<<1);
    

    reply permalink

  • Anonymous - 9 years, 3 months ago

    Python

    def doubler(n):
    
        a = 1
        numlength = 0
    
        while numlength < n:
            a *= 2
            numlength = len(str(a))
    
        return(a)
    
    print(doubler(32))
    
    

    Gives the answer: 10141204801825835211973625643008

    reply permalink

  • David - 8 years, 4 months ago

    While a decent idea, you have a 32 digit number, not a 32 bit number.

    reply permalink

  • Eddy - 9 years, 3 months ago

    My solution in C.

    reply permalink

Content curated by @MaxBurstein