Check if a number is formed by Concatenation of 1, 14 or 144 only in C++


Here we will see one problem, that can tell that whether a string or a number is a concatenation of 1, 14 or 144 only. Suppose a string is “111411441”, this is valid, but “144414” is not valid.

The task is simple, we have to fetch a single digit, double-digit and triple-digit number from the last, and check whether they match with any of these three (1, 14 and 144), if we get one match, divide the number with it, and repeat this process until the entire number is not exhausted.

Example

#include <iostream>
#include <cmath>
using namespace std;
bool checkNumber(long long number) {
   int n = number;
   while (n > 0) {
      if (n % 1000 == 144)
         n /= 1000;
         else if (n % 100 == 14)
            n /= 100;
         else if (n % 10 == 1)
            n /= 10;
      else {
         return false;
      }
   }
   return true;
}
int main() {
   long long n = 111411441;
   if(checkNumber(n)){
      cout << "Valid number";
   } else {
      cout << "Invalid number";
   }
}

Output

Valid number

Updated on: 21-Oct-2019

108 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements