Palindrometer

来源:互联网 发布:经典的java开源项目 编辑:程序博客网 时间:2024/06/11 05:20

Palindrometer

Description

While driving the other day, John looked down at his odometer, and it read 100000. John was pretty excited about that. But, just one mile further, the odometer read 100001, and John was REALLY excited! You see, John loves palindromes - things that read the same way forwards and backwards. So, given any odometer reading, what is the least number of miles John must drive before the odometer reading is a palindrome? For John, every odometer digit counts. If the odometer reading was 000121, he wouldn't consider that a palindrome. 

Input

There will be several test cases in the input. Each test case will consist of an odometer reading on its own line. Each odometer reading will be from 2 to 9 digits long. The odometer in question has the number of digits given in the input so, if the input is 00456, the odometer has 5 digits. There will be no spaces in the input, and no blank lines between input sets. The input will end with a line with a single 0. 

Output

For each test case, output the minimum number of miles John must drive before the odometer reading is a palindrome. This may be 0 if the number is already a palindrome. Output each integer on its own line, with no extra spaces and no blank lines between outputs. 

Sample Input

100000
100001
000121
00456
0

Sample Output

1
0
979
44


题意:读入一个数,问增加多少后是回文串

解法:直接暴力

#include <iostream>#include <string>#include <cstring>#include <stdio.h>using namespace std;char s[1000];int n;bool check(char* s) {    for (int i = 0; i <= n/2; i++)        if (s[i] != s[n-1-i]) return false;    return true;}int main() {    scanf("%s", s);    while (1) {        int ans = 0;        n = strlen(s);        if (s[0] == '0' && n == 1) break;        while (check(s) == false) {            s[n-1] = s[n-1]+1;            for (int i = n-1; i > 0; i--) {                if (s[i] > '9') {                    s[i] = '0';                    s[i-1] = s[i-1]+1;                } else break;            }            if (s[0] > '9') {                s[0] = '0';                for (int i = n; i > 0; i--)                    s[i] = s[i-1];                s[0] = '1';                n++;            }            ans++;        }        cout << ans << endl;        scanf("%s", s);    }}
0 0
原创粉丝点击