1060. Are They Equal (25)

题目地址:http://www.patest.cn/contests/pat-a-practise/1060

这题就是一道纯粹的字符串处理的题目,不过要考虑很多情况
特别是涉及到0的情况,还有是否是小数,做题的时候要列举多种不同的情况 如 00.00 ,0.001 ,1.00 ,0101.00 ,00111 ,00.101等等

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <vector>
#include <math.h>
#include <string>
#include <string.h>
#include <queue>
#include <unordered_map>
#include <algorithm>
#include <sstream>

using namespace std;


int n;
string s1;
string s2;

string s11, s22;
int n1, n2;

// 分小数 和 非小数处理 , 还要先去除一些不必要的0
void fun(string s1, string &s11, int & n1)
{
  s11 = "";
  int i = 0;

  if (s1.find('.') == string::npos)
  {
    while (s1[i] == '0')
    {
      i++;
    }
    s1 = s1.substr(i);

    n1 = s1.size();

    if (n1 <= n)
    {
      s11 = s1;
      for (i = 0; i < n - n1; i++)
      {
        s11 += '0';
      }
    }
    else{
      s11 = s1.substr(0, n);
    }

  }
  else{
    int dotPos = s1.find_first_of('.');
    i = 0;
    while (s1[i] == '0' && i < dotPos)
    {
      i++;
    }
    if (i == dotPos){
      s1 = "0" + s1.substr(i);
    }
    else{
      s1 = s1.substr(i);
    }

    i = 0;
    while (s1[i] == '0' || s1[i] == '.')
    {
      i++;
    }
    dotPos = s1.find_first_of('.');
    if (dotPos > i)
    {
      n1 = dotPos - i;
    }
    else{
      n1 = -(i - dotPos - 1);
    }
    int j;
    s11 = "";
    for (j = i; j < (int)s1.size() && (int)s11.size() < n; j++)
    {
      if (s1[j] != '.')
        s11 += s1[j];
    }

    if ((int)s11.size() < n)
    {
      for (i = 0; i < n - (int)s11.size(); i++)
      {
        s11 += '0';
      }
    }
  }
}

int main()
{
  //freopen("in", "r", stdin);
  while (scanf("%d",&n) != EOF)
  {
    cin >> s1;
    cin >> s2;
    int i;
    bool flag = false;
    for (i = 0; i < (int)s1.size(); i++)
    {
      if (s1[i] >= '1' && s1[i] <= '9')
      {
        flag = true;
        break;
      }
    }
    if (flag == false)
    {
      s11 = "";
      for (i = 0; i < n; i++)
      {
        s11 += "0";
      }
      n1 = 0;
    }
    else{
      fun(s1, s11, n1);
    }

    bool flag2 = false;
    for (i = 0; i < (int)s2.size(); i++)
    {
      if (s2[i] >= '1' && s2[i] <= '9')
      {
        flag2 = true;
        break;
      }
    }
    if (flag2 == false)
    {
      s22 = "";
      for (i = 0; i < n; i++)
      {
        s22 += "0";
      }
      n2 = 0;
    }
    else{
      fun(s2, s22, n2);
    }

    if (n1 == n2 && s11 == s22)
    {
      printf("YES 0.");
      cout << s11;
      printf("*10^%d\n",n1);
    }
    else{
      printf("NO ");

      printf("0.");
      cout << s11;
      printf("*10^%d ", n1);

      printf("0.");
      cout << s22;
      printf("*10^%d\n", n2);
    }
  }
  return 0;
}

你可能感兴趣的:(1060. Are They Equal (25))