PAT A1001 A+B Format
Sample Input:
-1000000 9
Sample Output:
-999,991
-
思路1:
将a+b的结果转化为字符串,再从后往前每3位加一个,
,每插入一个,
,记录已插入,
数的计数器++,使得下一次插入从后往前数逻辑上和没插入,
一样
分析:对任一非负数,插入,
数amount为len/3(当长度len刚好为3的倍数时,即len%3==0时,amount–);而对于负数,只需将-
忽略掉,只取数值部分,即长度为len-1 -
code1:
#include <iostream>
using namespace std;
int main(){
int x, y;
cin >> x >> y;
string s = to_string(x+y);
int len = s.size();
int count = 0;
if(s[0] == '-') len--;
if(len%3 == 0) len--;
//经过这两步化简,需插入,数即为:len/3
for(int i = 1; i <= len/3; ++i){
s.insert(s.end()-i*3-count, ',');
count++;
}
cout << s;
return 0;
}
-
思路2:
直接用一个for()逐位输出s,遇到s[0]==’-'的情况直接跳过,当下标i满足(len-i-1)%3==0
时,即:s[i]后的元素个数为3的倍数,输出完s[i]后接着输出一个,
,输出完最后一个元素后不输出,
,故判断条件还要加上i != len-1
-
code2:
#include <iostream>
using namespace std;
int main(){
int x, y;
cin >> x >> y;
string s = to_string(x+y);
int len = s.size();
for(int i = 0; i < len; ++i){
cout << s[i];
if(s[i] == '-') continue;
if((len-i-1)%3 == 0 && i != len-1) cout << ",";
//等价于:if((i+1)%3 == len%3 && i != len-1) cout << ",";
}
return 0;
}
- TIPS1:
0 1 2 3 |4| 5 6 |7| .. |x| .. |y|
x,y之间元素的个数为y-x-1,y-x的意义是:x之后再数(y-x)个数到y
所以len-i-1就是i之后元素的个数
- TIPS2: 取模运算规则
交换律:
(a + b) % p = (b+a) % p
(a * b) % p = (b * a) % p
分配律:
(a + b) % p = (a % p + b % p) % p
(a - b) % p = (a % p - b % p) % p
(a * b) % p = (a % p * b % p) % p
a ^ b % p = ((a % p)^b) % p
结合律:
((a+b) % p + c) % p = (a + (b+c) % p) % p
((a*b) % p * c)% p = (a * (b*c) % p) % p
重要定理:
若a≡b (% p),则对于任意的c,都有(a + c) ≡ (b + c) (%p);
若a≡b (% p),则对于任意的c,都有(a * c) ≡ (b * c) (%p);
若a≡b (% p),c≡d (% p),则:
(a + c) ≡ (b + d) (%p),
(a - c) ≡ (b - d) (%p),
(a * c) ≡ (b * d) (%p),
(a / c) ≡ (b / d) (%p);
- T3 code:
#include <bits/stdc++.h>
using namespace std;
int main()
{
int a, b;
scanf("%d %d", &a, &b);
int sum = a + b, sign = 1;
if(sum < 0)
{
sign = -1;
sum = -sum;
}
string ans = to_string(sum);
if(sign == -1) printf("-");
for(int i = 0; i < ans.size(); ++i)
{
int len = ans.size() - i;
if(len % 3 == 0 && i != 0) printf(",");
printf("%c", ans[i]);
}
return 0;
}
- T4 code:
#include <bits/stdc++.h>
using namespace std;
int main()
{
int a, b;
scanf("%d %d", &a, &b);
string ans = to_string(a+b);
for(int i = 0; i < ans.size(); ++i)
{
printf("%c", ans[i]);
if(ans[i] == '-' || i == ans.size()-1) continue;
if((ans.size()-1-i) % 3 == 0) printf(",");
}
return 0;
}