Home » Interview Questions » String Interview Questions » Check length of a string is equal to the number appended at its last

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

 

How useful was this post?

Click on a star to rate it!

Average rating / 5. Vote Count

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

READ  Integer to Roman
Array Interview Questions
Graph Interview Questions
LinkedList Interview Questions
String Interview Questions
Tree Interview Questions