-1

我试图解决 CodeChef 问题(问题链接 :: http://www.codechef.com/problems/K2)。代码应该为每个测试用例输入一个输入,处理,显示结果,然后再移动到下一个测试用例。但它只是接受输入而没有任何输出。我无法找出错误,因为 g++ 编译器没有给出任何错误。

#include <iostream>
#include <string>
#include <cstring>
#include <stdio.h>

using namespace std;
using std::string;

char baseArr[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};

bool isPalin(string number)
{
    int len=number.size();
    bool flag=true;
    for(int i=0; i<len/2, flag==true; i++)
    {
        if(number[i]==number[len-(i+1)])
            continue;
        else
        {
            flag=false;
        }
    }
    return flag;
}
string baseChange(long int number, int base)
{
    int i=1;
    int rem=0;
    string output =" ";
    while(number>0)
    {
        rem=number%base;
        number=number/base;
        output=baseArr[rem]+output;
    }
    return output;
}
int main()
{
    long int input;
    int testcase;
    string number;
    int i;
    bool palin=false;
    scanf("%d", &testcase);
    while(testcase--)
    {
        palin=false;
        scanf("%ld", &input);
        for(i=2; palin==false;i++)
            {
                {
                    palin=isPalin(baseChange(input, i));
                }
            }
        printf("%d\n",i);

    }
}
4

2 回答 2

2

您假设最大基数为 16,但情况可能并非如此。您可能会因为访问baseArr超出有效索引而遇到分段错误。我没有想到解决方案,但我相信可以在不考虑数字的任何字符值的情况下实现实际的解决方案。

于 2013-08-22T19:37:52.543 回答
0

回文问题的解决方案:

#include <sstream>
#include <cstdlib>

bool test_palindrome(const std::string& value)
{
    for (unsigned int i = 0; i < value.length() / 2; i++)
    {
        if (value[i] != value[value.length() - 1 - i])
            return false;
    }
    return true;
}

std::string find_palindrome(unsigned long num)
{
    std::string ret = "";
    for (int i = 2; i <= 32; i++)
    {
        char buffer[100] = {0};
        std::string value = ::itoa(num, buffer, i);
        std::cout << "Testing:  Base=" << i << " Value=" << value << std::endl;
        bool test = test_palindrome(value);
        if (test)
        {
            std::stringstream ss;
            ss << value << " (base " << i << ")";
            ret = ss.str();
            break;
        }
    }
    return ret;
}

int main()
{
    unsigned long input = 0;
    std::cout << "Enter number to search:  ";
    std::cin >> input;

    std::string palin = find_palindrome(input);

    std::cout << std::endl << "Palindrome Found:  " << palin << std::endl;

    return 0;
}
于 2013-08-22T20:51:03.977 回答