我正在努力解决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);
}
}
答案 0 :(得分:2)
您认为最大基数为16,但情况可能并非如此。您可能会因访问有效索引之外的baseArr
而出现分段错误。我没有想到解决方案,但我相信可以在不考虑数字的任何字符值的情况下实现实际解决方案。
答案 1 :(得分:0)
Palindrome问题的解决方案:
#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;
}