1. 程式人生 > >HDU 2057 A+B Again 手動解決辦法

HDU 2057 A+B Again 手動解決辦法

主要是坑在了空間釋放上QAQ,每次gets完之後進行處理,處理完之後必須得重新初始化字串!!!!

真的是大坑,,一道水題做了一晚上……


題目如下:

A+B Again


Problem Description There must be many A + B problems in our HDOJ , now a new one is coming.
Give you two hexadecimal integers , your task is to calculate the sum of them,and print it in hexadecimal too.
Easy ? AC it !
 
Input The input contains several test cases, please process to the end of the file.
Each case consists of two hexadecimal integers A and B in a line seperated by a blank.
The length of A and B is less than 15.
 
Output For each test case,print the sum of A and B in hexadecimal in one line.

 
Sample Input

  
   +A -A+1A 121A -9-1A -121A -AA
  
 
 
   
 
 
Sample Output

  
   02C11-2C-90
  
 
 


一般方法是這樣的:

  1. #include<stdio.h>  
  2. int main()  
  3. {  
  4.     long long n,m,v;  
  5.     while(scanf("%llx%llx",&n,&m)==2)  
  6.     {  
  7.         v=n+m;  
  8.         if(v<0)  
  9.         {  
  10.             v=-v;  
  11.             printf("-%llX\n",v);      
  12.         }  
  13.         else  
  14.         printf("%llX\n",v);   
  15.     }    
  16.      return 0;  
  17.  }   

我跳的坑是這樣的:

<textarea readonly="readonly" name="code" class="c++"> 
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
    char s[50]={'\0'};
    long long int x=0,y=0,z=0;
    while(gets(s)!=NULL)
    {
       int l = strlen(s);
       int i=l-1;
       long long int k=1;
       //scanf("%llx%llx",&a,&b);
       char c=s[i];
       //printf("length=%d\n",l);
       while(c!=' ')
       {
           //printf("%c ",c);
           if(c=='-')x=-x;
           if(c!='+' && c!='-'){
                if(c<65)x+=(c-48)*k;
                else if(c<97)x+=(c-55)*k;
                     else x+=(c-87)*k;
           }
           k=k*16;
           i--;
           //printf("%c %llX and",c,x);
           c=s[i];
       }
       k=1;
       //printf("i=%d\n",i);
       i--;
       c=s[i];
      // printf("\n");
       while(i>=0)
       {

           if(c=='-')y=-y;
           if(c!='+' && c!='-'){
                if(c<65)y+=(c-48)*k;
                else if(c<97) y+=(c-55)*k;
                     else y+=(c-87)*k;
           }
           k=k*16;
           i--;
           //printf("%c %llX and",c,y);
           c=s[i];
       }
       //printf("\n");
       z=x+y;
       if(z<0)printf("-%llX\n",-z);
       else printf("%llX\n",z);
       x=0;y=0;z=0;
       for(i=0;i<50;i++)s[i]='\0';
    }
    //free(s);
    return 0;
}
</textarea>

emmm最後還是AC瞭然而那個大坑是真心不容易跳出來

總結一句,初始化hin重要!!!