有些內容使用中英雙語,有些只有英文或中文。歡迎使用與分享任何內容,但先來信告知並標示此部落格為出處。
Some parts use both Chinese and English, but some parts use only one language. Feel free to share, but please contact me first and list this blog as your reference.

2014年2月27日 星期四

UVa OJ - 10018 Reverse and Add

The following program is my ACcepted code for UVA-10018.
It's a for everybody to learn and discuss.
If there is any mistake or comment, please let me know.  :D

此乃UVA 10018 的AC code!
歡迎一同討論學習,如有錯誤與任何建議請留言 : )

點這裡看題目 Click here to see this Problem!


//This program is for UVA 10018 Reverse and Add
//http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=12&page=show_problem&problem=959

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
using namespace std;

/*
a palindrome that is not greater than 4,294,967,295.
the "int" type range: -2,147,483,648 ~ 2,147,483,647
so I use the "long long int": -9223372036854775808 ~ 9223372036854775807
or
you may also use the "unsigned int": 0 ~ 4,294,967,295.
*/

//reverse an number
int reverse(long long int a)
{
    char s1[25], s2[25];
 
    //char *  itoa ( int value, char * str, int base ); base代表幾進位
    sprintf(s1, "%lld", a);
 
    int len = strlen(s1);
 
    for(int i=0; i<len; i++)
        s2[i] = s1[len -1 -i];
    s2[len] = '\0';
 
    return atoi(s2);
}

//check if the number is a palindrome!
bool isPal(long long int a)
{
    char s[25];
    sprintf(s, "%lld", a);//save as array
 
    int len = strlen(s);
    int halfLen = len / 2;
 
    for(int i=0; i < halfLen; i++)//start 0 and end in len-1
    {
        if(s[i] != s[len - 1 - i])
            return false;
    }
    return true;
}

void findAns(long long int x)
{
    long long int y, add = 0;
 
    do
    {
        y = reverse(x);
        x = x + y;
        add ++;
    }while(isPal(x) == false);
 
    printf("%lld %lld\n", add, x);
 
    return;
}

int main()
{
    long long int n, m;
 
    while(scanf("%lld", &n) != EOF)
    {
        while(n--)
        {
            scanf("%lld", &m);
            findAns(m);
        }
    }
    return 0;
}

Please feel free to use it after adding this blog as an reference. (http://autekroy.blogspot.tw) If there is any mistake or comment, please let me know. :D 

歡迎使用與分享任何內容,但請記得標示此部落格為出處。(http://autekroy.blogspot.tw/) 如果有發現任何的錯誤與建議請留言或跟我連絡。 : )

沒有留言:

張貼留言

請留下您的任何想法或建議!
Please leave any thought or comment!