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

ตรวจสอบว่า a + b =c ถูกต้องหรือไม่หลังจากลบศูนย์ทั้งหมดออกจาก a, b และ c ใน C++


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

เราจะลบ 0 ทั้งหมดออกจากตัวเลข จากนั้นเราจะตรวจสอบหลังจากลบ 0s แล้ว a + b =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) { //if the last digit is 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