2014年2月27日 星期四

UVa OJ - 10035 Primary Arithmetic

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

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

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


//This program is for UVA 10035 Primary Arithmetic
//http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=12&page=show_problem&problem=976

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

char s1[15], s2[15], a[15], b[15];
int len1, len2;

//it's just for checking the index and values
void checkPrint()
{
    printf("%d %d\n", len1, len2);
 
    for(int i=0 ; i <= 14; i++)
        printf("%c", a[i]);
    printf("\n");

    for(int i=0 ; i <= 14; i++)
        printf("%c", b[i]);
    printf("\n");  
}

// move s1 and s2 to aother array (beginning from the rightese index)
void move()
{          
    for(int i=0; i<= 14; i++)
    {
        a[i] = '0';
        b[i] = '0';
    }
 
    for(int i=0 ; i <= 14; i++)
    {
        a[14 - i] = s1[ len1 - 1 - i];
        if( (len1 - 1 - i) == 0)
            break;  
    }
 
    for(int i=0 ; i <= 14; i++)
    {
        b[14 - i] = s2[ len2 - 1 - i];
        if( (len2 - 1 - i) == 0)
            break;  
    }  
}

/*
    first move s1 and s2 to aother array (beginning from the rightese index)
    and then we can perform the basic add function for each index from right to lest index.
*/
void findCarry()
{
    int carry = 0;
    int add[15];
 
    //move s1 and s2!!
    move();
    //checkPrint();
 
    memset(add, 0, sizeof(add));
 
    for(int i = 14; i >= 1; i--)
    {
        add[i] += (a[i]-'0') + (b[i]-'0');

        if(add[i] >= 10)
        {
            add[i - 1] ++;
            add[i] -= 10;
            carry ++;
        }
    }
 
    /*
    //check add
    for(int i=0 ; i <= 14; i++)
        printf("%d", add[i]);
    printf("\n");*/
 
    if(carry == 0)
        printf("No carry operation.\n");
    else if(carry == 1)
        printf("1 carry operation.\n");
    else
        printf("%d carry operations.\n", carry);
     
    return;
}

int main()
{
    while(scanf("%s %s", &s1, &s2) != EOF)
    {
        len1 = strlen(s1);
        len2 = strlen(s2);
     
        if(len1 == 1 && len2 == 1 && s1[0] == '0' && s2[0] == '0')//the input are 0 0
            break;
     
        findCarry();
    }
    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!