在C++中,移除a、b和c中的所有零後,檢查a + b = c是否有效


假設我們有三個數字a、b、c,我們需要檢查在移除所有數字中的0之後,a + b = c是否成立。例如,數字為a = 102,b = 130,c = 2005,則移除0後,a + b = c變為:(12 + 13 = 25),這是正確的。

我們將移除一個數字中的所有0,然後檢查移除0後,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

更新於: 2019年10月21日

65 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.