Sum is same for first and last three digits

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.IO;

 

namespace ConsoleApplication2

{

    class Program

    {

        static void Main(string[] args)

        {

            StreamWriter sw = new StreamWriter(@"D:\Numbers.txt", false);

            //Find all numbers in the range 111111…999999 where sum of first 3 digits is same as last 3 digits

            for (int i = 111111; i <= 999999; i++)

            {

                if (Check(i))

                {

                    Console.WriteLine(i.ToString());

                    sw.WriteLine(i.ToString());

                }

            }

            sw.Close();

        }

        public static bool Check(int num)

        {

            string str = num.ToString();

            if (str.Length < 6)

            {

                return false;

            }

            else

            {

                int temp = 0;

                for (int i = 0; i < 3; i++)

                {

                    temp = temp + int.Parse(str[i].ToString());

                }

                for (int i = str.Length – 1; i > (str.Length – 1 – 3); i–)

                {

                    temp = temp – int.Parse(str[i].ToString());

                }

                if (temp == 0)

                {

                    return true;

                }

                else

                {

                    return false;

                }

            }

        }

    }

}

Advertisements
This entry was posted in Information Technology. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s