Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Kiểm tra a+b=c sau khi xóa số 0 trong C++


Cho ba số a, b, c. Kiểm tra a + b = c có đúng sau khi xóa tất cả chữ số 0 khỏi ba số hay không. Ví dụ a=102, b=130, c=2005 → sau khi xóa 0: 12 + 13 = 25 → đúng.

Hàm xóa số 0: duyệt chữ số từ cuối, xây số mới bỏ qua chữ số 0.

Ví dụ

#include <iostream>
#include <algorithm>
using namespace std;

int deleteZeros(int n) {
    int res = 0, place = 1;
    while (n > 0) {
        if (n % 10 != 0) {
            res += (n % 10) * place;
            place *= 10;
        }
        n /= 10;
    }
    return res;
}

bool isSame(int a, int b, int c){
    return (deleteZeros(a) + deleteZeros(b) == deleteZeros(c));
}

int main() {
    int a = 102, b = 130, c = 2005;
    if(isSame(a, b, c))
        cout << "a + b = c is maintained";
    else
        cout << "a + b = c is not maintained";
}

Kết quả

a + b = c is maintained