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

前端 未结 17 994
天涯浪人
天涯浪人 2021-02-02 04:27
package testing.project;

public class PalindromeThreeDigits {

    public static void main(String[] args) {
        int value = 0;
        for(int i = 100;i <=999;i+         


        
17条回答
  •  被撕碎了的回忆
    2021-02-02 05:05

    A slightly different approach that can easily calculate the largest palindromic number made from the product of up to two 6-digit numbers.

    The first part is to create a generator of palindrome numbers. So there is no need to check if a number is palindromic, the second part is a simple loop.

    #include 
    #include 
    #include 
    
    using namespace std;
    template 
    class PalindromeGenerator {
        unique_ptr  m_data;
        bool m_hasnext;
    public :
        PalindromeGenerator():m_data(new int[N])
        {
            for(auto i=0;i=0;i--){
            v+=m_data[i]*b;
            b*=10;
        }
    
        auto i=N-1;
        while (i>=0)
        {
            if(m_data[i]>=1) {
                m_data[i]--;
                return v;
            }
            else 
            {
                m_data[i]=9;
               i--; 
            }
        }
    
        m_hasnext=false;
        return v;
    }
    
    
    };
    
    template
    void findmaxPalindrome()
    {
        PalindromeGenerator gen;
        decltype(gen.getnext()) minv=static_cast (pow(10,N-1));
        decltype(gen.getnext()) maxv=static_cast (pow(10,N)-1);
        decltype(gen.getnext()) start=11*(maxv/11);
        while(gen.hasNext())
        {
            auto v=gen.getnext();
            for (decltype(gen.getnext())  i=start;i>minv;i-=11)
            {
                if (v%i==0)
                {
                    auto r=v/i;
                    if (r>minv && r();
        return 0;
    }
    

提交回复
热议问题