PAT甲级1060 Are They Equal (25分)|C++实现

一、题目描述

原题链接
在这里插入图片描述

Input Specification:

在这里插入图片描述

​​Output Specification:

在这里插入图片描述

Sample Input 1:

3 12300 12358.9

Sample Output 1:

YES 0.123*10^5

Sample Input 2:

3 120 128

Sample Output 2:

NO 0.120*10^3 0.128*10^3

二、解题思路

稍微有点复杂的字符串处理题,只要把握好数字标准形式的变化规律,还是很容易做出来的,这道题有一个小坑,就是前导0要消去,0000120要先变为120再进行转换,具体请看代码注释。

三、AC代码

#include<iostream>
#include<cstdio>
#include<string>
#include<algorithm>
#include<vector>
using namespace std;
string change(string str, int N)    //变为标准形式
{
    
    
  int exp = 0, cnt = 0, posdot = -1, sze;   //指数数值大小,当前有效数字,小数点的位置,字符串长度
  string valid; //最终有效的字符串
  if(str[0] == '-') //初始化valid
  {
    
    
    valid = "-0.";
    str.erase(str.begin());
  }
  else	valid = "0.";
  while(str[0] == '0')  str.erase(str.begin()); //去除前导0
  if(str[0] == '.') //小数
  {
    
    
    sze = str.size();
    for(int i=1; i<sze; i++)
    {
    
    
      if(str[i] == '0') exp--;  //每经过一个0,exp--
      else
      {
    
    
        if(cnt < N)
        {
    
    
          valid += str[i];
          cnt++;
        }
        else	break;
      }
    }
  }
  else
  {
    
    
    sze = str.size();
    for(int i=0; i<sze; i++)
    {
    
    
      if(str[i]>='0' && str[i]<='9' && posdot == -1)    //还未经过小数点
      {
    
    
        if(cnt < N)
        {
    
    
          valid += str[i];
          cnt++;          
        }
        exp++;  //每经过一个数 exp++
      }
      else if(str[i] == '.')	posdot = i; //找到小数点位置
      else
      {
    
    
        if(cnt<N)
        {
    
    
          valid += str[i];
          cnt++;
        }
        else	break;
      }
    }
  }
  if(cnt == 0)	exp = 0;
  while(cnt < N)//补0
  {
    
    
    valid += '0';
    cnt++;
  }
  valid += "*10^";
  valid += to_string(exp);
  return valid;
}
int main()
{
    
    
  int N;
  scanf("%d", &N);
  string num1, num2;
  cin >> num1 >> num2;
  num1 = change(num1, N);
  num2 = change(num2, N);
  if(num1 == num2)
    printf("YES %s", num1.c_str());
  else	printf("NO %s %s", num1.c_str(), num2.c_str());
  return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42393947/article/details/108637822