代码改变世界

【欧拉题四】三位数乘积所得的最大回文数

2012-03-10 02:11  撞破南墙  阅读(404)  评论(0编辑  收藏  举报


题目

 

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 ×99.

Find the largest palindrome made from the product of two 3-digit numbers.

 

代码 

 using System;

using System.Collections.Generic;

/*
 * 
 * 从 X1=999 ,X2=999
 * 判断乘积是否回文转换成字符串, 
 * 依次减 X1和X2  
 * 
 * 
*/
namespace OulerProblem
{
    public class Problem4
    {
         
        public static string  q4 ()
        {
            List<int> list=new List<int> ();
            int x1 = 999, x2 = 999;
            bool isok = false;
            for (int k = x1 ; k >= 1; k--) {                
                for (int j = x2 ; j >= 1; j--) {
                    
                    string palNum = (k * j).ToString ();
                     
                    isok = isStringP (palNum);
                    if (isok) {
                        list.Add(k*j);
                         
                    }     
                }
                     
                
            }
                 
                list.Sort();
            
            return ""+list[list.Count-1] ;    
        }

        public static  bool isStringP (string palNum)
        {
            bool isok = false;
            var array1 = palNum.ToCharArray ();
            int last = array1.Length - 1;
            int i = 0;
         
            while (true) {//单个字符相等                
                if (array1 [i] != array1 [last - i]) {                     
                    break;
                }  
                if (i == array1.Length - i || i == array1.Length - i - 1) {                         
                    isok = true;
                    break;
                }                
                i++;
            }
            return isok;
        }

        public static void test ()
        {
            //    Console.WriteLine (isStringP ((99 * 91).ToString ()));
            
            var t1 = DateTime.Now;
            Console.WriteLine (" " + q4 () + " cast time " + (DateTime.Now - t1).TotalSeconds);

        }
    }
}