Check if a + b = c is valid after removing all zeroes from a, b and c in C++



Suppose we have three numbers a, b, c, we have to check whether a + b = c, after removing all 0s from the numbers or not. Suppose the numbers are a = 102, b = 130, c = 2005, then after removing 0s, the numbers will be a + b = c : (12 + 13 = 25) this is true

We will remove all 0s from a number, then we will check after removing 0s, a + b = c or not.

Example

 Live Demo

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

Output

a + b = c is maintained
Updated on: 2019-10-21T08:53:27+05:30

118 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements