1. 程式人生 > >HDU 1228 A + B(來吧,互相傷害)

HDU 1228 A + B(來吧,互相傷害)

有點辣眼睛,還有兩個部分也可以函式化,那樣的話,程式碼還是可以少很多的。

大致思路就是+號前和後兩部分放到兩個二維陣列,然後轉化為數值相加即可


#include<stdio.h>
#include<string.h>

char value[10][6]={"zero","one","two","three","four","five","six","seven","eight","nine"};
char ch1[4][10], ch2[4][10];
char ch[100];

int sum(int * temp, int t) {
  int num1 = 0, ten = 10;
  for (int i = t-2, s = 1; i >= 0; i--) {
    ten *= s;
    num1 += temp[i] * ten;
    s*=10;
  }
  num1 += temp[t-1];
  return num1;
}

int main(void)
{
  
  while (gets(ch) != NULL) {
    int i, j, a[4] = {0}, k = 0, c = 0, temp[4] = {0};
    for (i = 0; ch[i]!='+'; i++) {
      if (ch[i] != ' ') {
        ch1[k][a[c]++] = ch[i];
      } else {
        ch1[k][a[c]] = '\0';
        k++;
        c++;

      }
    }
    int t = 0;
    for (int i = 0; i < k; i++) {
      for (int j = 0; j < 10; j++) {
        if (strcmp(ch1[i], value[j]) == 0) {
          temp[t] = j;
          t++;
          break;
        }
      }

    }
    int num1 = sum(temp, t);
    
    int b[4] = {0};
    c = 0, k = 0;
    for (int j = i+2; ch[j] != '='; j++) {
      if (ch[j] != ' ') {
        ch2[k][b[c]++] = ch[j];
      } else {
        ch2[k][b[c]] = '\0';
        k++;
        c++;
      }
    }

    t = 0;
    memset(temp, 0, sizeof(temp));
    for (int i = 0; i < k; i++) {
      for (int j = 0; j < 10; j++) {
        if (strcmp(ch2[i], value[j]) == 0) {
          temp[t] = j;
          t++;
          break;
        }
      }
    }
    int num2 = sum(temp, t);

    if (!num1 && !num2) {
      break;
    }
    printf("%d\n", num2+num1);

  }

  return 0;
}