0

我制作了这段代码,它应该增加一个数字,直到获得这个输入数字的下一个回文数。

该程序将数字作为字符串“因为它可能是一个非常大的数字( 0 < 数字 < 1000000 )” ....

编码

int main ()
{
string number = "1243";
int position = number.length()-1;
do
{
    if (number[position] == '9')
    {
        //cout << "hereee";
        number[position] = '0';
        int n1 = (int)number[position-1] - '0';
        n1++;
        number[position-1] = n1 + '0';
        nextPalindrome[position-1];
         cout << number <<"hereee2"<< endl; // only to determine if i get in "if"
    }
    else
    {
        int n1 = (int)number[position] - '0';
        n1++;
        number[position] = n1 + '0';
        cout << number <<"hereee1" << endl; // only to determine if i get in "else"
    }
} while (isPalindrome(number) == false);
}

它开始获取当前位置的数字并将其递增并再次将其作为字符返回

问题

cout << number <<"hereee1" << endl;

此行显示运行时的号码状态,就像这样:

12"6 hereee1

12"7 hereee1

12"8 hereee1

12"9 hereee1

12#0 hereee2

12#1 hereee1

虽然它必须是

1236 hereee1

1237 hereee1

1238 hereee1

1239 hereee1

1240 hereee2

1241 hereee1

我不知道错误在哪里..有人可以帮忙吗

注意: “isPalindrome”是一个以字符串为参数的函数,如果原始字符串等于其反向,则返回 true .. 否则返回 false

4

2 回答 2

3

What is the result of this when the digit at position-1 is '9'?

    int n1 = (int)number[position-1] - '0';
    n1++;
    number[position-1] = n1 + '0';
于 2013-01-29T12:49:58.490 回答
1

You don't handle carryover well... This part is invalid:

    int n1 = (int)number[position-1] - '0';
    n1++;
    number[position-1] = n1 + '0';

This just increases the digit on the previous place. And if it happens to be '9' (same as what Mats Petersson tried to suggest), it just overflows... It should however be carried over to the next digit too... This is a recursive solution to this (beware, there might be syntax errors, I haven't coded in C++ since ages...):

/*
* This function adds one to the specified digit of a 
* string containing a decimal integer.
*
* Contains no checks whatsoever. Behavior is undefined when 
* not supplied a valid input string.
*/
int addOneToDigit (string number, int digit)
{
    if (number[digit] == '9')
    {
        number[digit] = '0';
        //we need to handle getting a longer string too...
        if(digit>0) 
        {
            return addOneToDigit(number, digit-1);
        }
        else
        {
            return "1" + number;
        }
    }
    else
    {
        int n1 = (int)number[digit] - '0';
        n1++;
        number[digit] = n1 + '0';
    }
    return number;
}

and the main() would look like something like this:

int main ()
{
    string number = "1243";
    do
    {
      number = addOneToDigit(number,number.length()-1)
    } 
    while (isPalindrome(number) == false);
}
于 2013-01-29T13:00:23.553 回答