练习cf75A. Life Without Zeros
题目如下
A. Life Without Zeros
time limit per test2 seconds
memory limit per test256 megabytes
Can you imagine our life if we removed all zeros from it? For sure we will have many problems.
In this problem we will have a simple example if we removed all zeros from our life, it's the addition operation. Let's assume you are given this equation a + b = c, where a and b are positive integers, and c is the sum of a and b. Now let's remove all zeros from this equation. Will the equation remain correct after removing all zeros?
For example if the equation is 101 + 102 = 203, if we removed all zeros it will be 11 + 12 = 23 which is still a correct equation.
But if the equation is 105 + 106 = 211, if we removed all zeros it will be 15 + 16 = 211 which is not a correct equation.
Input
The input will consist of two lines, the first line will contain the integer a, and the second line will contain the integer b which are in the equation as described above (1 ≤ a, b ≤ 109). There won't be any leading zeros in both. The value of c should be calculated as c = a + b.
Output
The output will be just one line, you should print "YES" if the equation will remain correct after removing all zeros, and print "NO" otherwise.
题目大意
现有两个数a,b都含有0,把他们相加得到的数去0后得到一个新的数,若把在相加之前就把a,b各自去0,得到的数是否相同
若要对一个数进行去 0 的操作,可以先用string的类型表示,根据string可以自由增删的特性,先把串中出现的 0 都删去,得到去 0 版的数再通过stoi函数把string转换为整数
点击查看代码
string remove_zero(string s) {
string ss = "";
for(int i = 0; i < s.size(); i++){
char c = s[i];
if(c != '0'){
ss += c;
}
}
return ss;
}
先把a,b各自转化为整数相加后得到c,对c进行转化为string操作后获得再进行去0操作获得新的c_no0(此时是string类型),最后是两个数比较,所以再进行一次转换得到数字c1;
c2则直接把去0后的a得到的aa和b去0后得到的bb直接转化得到c2;
再把两个数比较,符合题意
完整代码
点击查看代码
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string remove_zero(string s) {
string ss = "";
for(int i = 0; i < s.size(); i++){
char c = s[i];
if(c != '0'){
ss += c;
}
}
return ss;
}
int main(){
string a, b;
cin >> a >> b;
int c = stoi(a) + stoi(b); //把串a,b转化为数字相加得出初始的c的值
string c_no0 = remove_zero(to_string(c)); //把a和b相加后的数也去0
int c1 = stoi(c_no0);
string aa = remove_zero(a);
string bb = remove_zero(b);
int c2 = stoi(aa) + stoi(bb); //把串aa,bb转化为数字相加得出去0后的c2的值
if(c1 == c2){
printf("YES\n");
}else{
printf("NO\n");
}
return 0;
}//
注意本题的类型转换

浙公网安备 33010602011771号