PAT-乙-1048 1048 数字加密 (20 分)

在这里插入图片描述

代码

#include <iostream>

using namespace std;

int main() {

	string s1, s2;
	cin>>s1>>s2;

	//put the length same
	while(s1.length()<s2.length()) {
		s1 = "0" + s1;
	}
	while(s2.length()<s1.length()) {
		s2 = "0" + s2;
	}

	string ans;
	int pos = 1;
	string reminder = "0123456789JQK";
	for(int i=s1.length()-1; i>=0; i--) {
		if(pos%2) {
			ans += reminder.at((s1.at(i)-'0'+s2.at(i)-'0')%13);
		} else {
			// >=0 , not > 0, otherwise there will be 3 wrong answer cases!
			ans += s2.at(i)-s1.at(i)>=0?s2.at(i)-s1.at(i)+'0':s2.at(i)-s1.at(i)+'0'+10;
		}
		pos++;
	}

	for(int i=ans.length()-1; i>=0; i--) {
		cout<<ans.at(i);
	}
	cout<<endl;

	return 0;
}

注解

1、细节决定成败,读题很重要!!一开始一直是15分,有3个案例错误,找了很久都没找到。后来发现原题是:对偶数位,用 B 的数字减去 A 的数字,若结果为负数,则再加 10。这里令个位为第 1 位。
负数!所以应该是s2-s1>=0,而我这里一开始写成了s2-s1>0。于是s2-s1==0的情况就会多加了10,难怪会有三个案例错误!

// >=0 , not > 0, otherwise there will be 3 wrong answer cases!
ans += s2.at(i)-s1.at(i)>=0?s2.at(i)-s1.at(i)+'0':s2.at(i)-s1.at(i)+'0'+10;

2、要考虑s1与s2长度不一致的情况,解决办法是开头补0,直到二者长度一致。

结果

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值