PAT A1060 Are They Equal简单思路

题目链接

这道题想做满分其实是有点难度的,不过得个20分不算太难,《算法笔记》上的思路挺清楚的,如下:

#include <iostream>
#include <string>
using namespace std;
int n;
string deal(string s, int &e){
	int k=0; 
	while (s.length()>0 && s[0]=='0'){
		s.erase(s.begin());
	}
	if (s[0]=='.'){
		s.erase(s.begin());
		while (s.length()>0 && s[0]=='0'){
			s.erase(s.begin());
			e--;
		}
	}else {
		while (k<s.length() && s[k]!='.'){
			k++;
			e++;
		}
		if (k<s.length()){
			s.erase(s.begin()+k);
		}
	}
	if (s.length()==0){
		e=0;
	}
	int num=0;
	k=0;
	string res;
	while (num<n){
		if (k<s.length()) {
			res+=s[k++];
		}else {
			res+='0';
		}
		num++;
	}
	return res;
} 
int main(){
	string s1,s2,s3,s4;
	cin>>n>>s1>>s2;
	int e1=0,e2=0;
	s3=deal(s1,e1);
	s4=deal(s2,e2);
	if (s3==s4 && e1==e2){
		cout<<"YES 0."<<s3<<"*10^"<<e1<<endl;
	}else {
		cout<<"NO 0."<<s3<<"*10^"<<e1<<" 0."<<s4<<"*10^"<<e2<<endl;
	}
}

但其实还可以思路更傻瓜一点,deal 函数的重点不在于他的返回值,而在于这个指数e, 小数点的判断完全可以用find方法直接解决,如下:

#include <iostream>
#include <cstdio>
#include <string>
using namespace std;
int n;
string deal(string a, int &e){
	string ans="0.";
	e=0;
	while (a.length()>0 && a[0]=='0'){
		a.erase(a.begin());
	} 
	int pos=a.find(".");
	if (pos==a.npos){
		e=a.length();
	}else if (pos==0){
		a.erase(a.begin());
		while (a.length()>0 && a[0]=='0'){
			a.erase(a.begin());
			e--;
		}
	}else{
		a.erase(pos,1);
		e=pos;
	}
	if (a.length()==0){
		e=0;
	}
	int k=0;
	while (k<n){
		if (k<a.length()){
			ans+=a[k];
		} else {
			ans+='0';
		}
		k++;
	}
	ans+="*10^";
	return ans;
}
int main(){
	string s1,s2;
	cin>>n>>s1>>s2;
	int e1,e2;
	string s3=deal(s1,e1);
	string s4=deal(s2,e2);
	if (s3==s4 && e1==e2){
		cout<<"YES "<<s3<<e1<<endl;
	}else {
		cout<<"NO "<<s3<<e1<<" "<<s4<<e2<<endl;
	}
}

STL真是太方便了!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值