Comparing Two Long Integers

You are given two very long integers a, b (leading zeroes are allowed). You should check what number a or b is greater or determine that they are equal.

The input size is very large so don’t use the reading of symbols one by one. Instead of that use the reading of a whole line or token.

As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java. Don’t use the function input() in Python2 instead of it use the function raw_input().

Input

The first line contains a non-negative integer a.

The second line contains a non-negative integer b.

The numbers a, b may contain leading zeroes. Each of them contains no more than 106 digits.
这里写图片描述

这里写图片描述

题目大意:

比较两个数字的大小,数字可能包含前缀0。

解题思路:

先对字符串前面的0进行一个预处理,得到数字实际长度,然后对长度相等的串逐个比较。本题在第14个样例上WA了n次,原因在于对于两个字符相同的情况处理用了一个骚操作,忽略了后自增运算符和相等关系运算符的优先级问题,后来改正就AC了。。。虽然还是不明白和第14个样例有啥关系。。
代码如下:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
char a[10000010],b[10000010];
int main()
{
  scanf("%s %s",a,b);
  int cur1=0,cur2=0;
  bool flag1=false,flag2=false;
  for(int i=0;i<strlen(a);i++)
  {
    if(a[i]=='0')cur1++;
    else  break;
  }
  for(int i=0;i<strlen(b);i++)
  {
    if(b[i]=='0')cur2++;
    else break;
  }
  int lena=strlen(a)-cur1,lenb=strlen(b)-cur2;
  if(lena<lenb)cout<<'<'<<endl;
  else if(lena>lenb)cout<<'>'<<endl;
  else
  {
    while(cur1<strlen(a)&&cur2<strlen(b))
    {
      if(a[cur1]==b[cur2])//错误写法a[cur1++]==b[cur2++];就这里WA了n次
      {
        cur1++;
        cur2++;
      }
      else if(a[cur1]>b[cur2])
      {
        cout<<'>'<<endl;
        return 0;
      }
      else
      {
        cout<<'<'<<endl;
        return 0;
      }
    }
    cout<<'='<<endl;
  }
}

猜你喜欢

转载自blog.csdn.net/A7_RIPPER/article/details/81460951