Check length of a string is equal to the number appended at its last

Given a string that is appended with a number at last, write a function that checks whether the length of the string excluding the number is same as the number or not.

Example

INPUT
s = "cat3"

OUTPUT
TRUE

Algorithm

1. Traverse the string from end

2. Find the number and store it and compare that number with the length of the remaining string

3. If yes, return TRUE

C++ Program

#include<bits/stdc++.h>
using namespace std;
 

bool isEqual(string s)
{
    int n = s.length();
 
    //Traverse from end of the string
    //x is to find the number
    int num = 0, x = 1, i = n-1;
    for (i=n-1; i>=0; i--)
    {
        if ('0' <= s[i] &&  s[i]  <= '9')
        {
            num = (s[i] - '0')*x + num;
            x = x * 10;
        }
        else break;
    }
 
    // compare length and number
    return num == i+1;
}


int main()
{
    string s = "cat3";
    if(isEqual(s))
    {
        cout << "Yes"<<endl; 
    }
    else
    {
        cout << "No"<<endl;
    }
    return 0;
}
Try It

 


Next > < Prev
Scroll to Top