Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ตรวจสอบ a+b=c หลัง Remove Zeroes ใน C++

สมมติมี a, b, c ต้องตรวจสอบว่า a + b = c หลัง Remove 0 ทั้งหมดจากตัวเลข ตัวอย่าง a=102, b=130, c=2005 หลัง Remove 0s: 12 + 13 = 25 เป็นจริง

Remove 0s จาก Numbers แล้วเช็ค a + b = c

ตัวอย่างโค้ด C++

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

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

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

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";
}

ผลลัพธ์

a + b = c is maintained