Open In App

Check if a number ends with another number or not

Last Updated : 08 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given two numbers A and B where (A > B), the task is to check if B is a suffix of A or not. Print “Yes” if it is a suffix Else print “No”.
Examples: 

Input: A = 12345, B = 45 
Output: Yes
Input: A = 12345, B = 123 
Output: No 

Method 1: 

  1. Convert the given numbers A and B to strings str1 and str2 respectively.
  2. Traverse both the strings from the end of the strings.
  3. While traversing the strings, if at any index characters from str1 and str2 are unequal then print “No”.
  4. Else print “Yes”.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include "bits/stdc++.h"
using namespace std;
 
// Function to check if B is a
// suffix of A or not
bool checkSuffix(int A, int B)
{
 
    // Convert numbers into strings
    string s1 = to_string(A);
    string s2 = to_string(B);
 
    // Find the lengths of strings
    // s1 and s2
    int n1 = s1.length();
    int n2 = s2.length();
 
    // Base Case
    if (n1 < n2) {
        return false;
    }
 
    // Traverse the strings s1 & s2
    for (int i = 0; i < n2; i++) {
 
        // If at any index characters
        // are unequals then return false
        if (s1[n1 - i - 1]
            != s2[n2 - i - 1]) {
            return false;
        }
    }
 
    // Return true
    return true;
}
 
// Driver Code
int main()
{
    // Given numbers
    int A = 12345, B = 45;
 
    // Function Call
    bool result = checkSuffix(A, B);
 
    // If B is a suffix of A, then
    // print "Yes"
    if (result) {
        cout << "Yes";
    }
    else {
        cout << "No";
    }
    return 0;
}


Java




// Java program for the above approach
class GFG{
     
// Function to check if B  
// is a suffix of A or not
public static boolean checkSuffix(int A,
                                  int B)
{
     
    // Convert numbers into strings
    String s1 = String.valueOf(A);
    String s2 = String.valueOf(B);
     
    // Find the lengths of strings
    // s1 and s2
    int n1 = s1.length();
    int n2 = s2.length();
     
    // Base case
    if (n1 < n2)
    {
        return false;
    }
     
    // Traverse the strings s1 & s2
    for(int i = 0; i < n2; i++)
    {
         
       // If at any index characters
       // are unequals then return false
       if (s1.charAt(n1 - i - 1) !=
           s2.charAt(n2 - i - 1))
       {
           return false;
       }
    }
     
    // Return true
    return true;
}
 
// Driver code
public static void main(String[] args)
{
         
    // Given numbers
    int A = 12345, B = 45;
     
    // Function Call
    boolean result = checkSuffix(A, B);
     
    // If B is a suffix of A, 
    // then print "Yes"
    if (result)
    {
        System.out.print("Yes");
    }
    else
    {
        System.out.println("No");
    }
}
}
 
// This code is contributed by divyeshrabadiya07


Python3




# Python3 program for the above approach
 
# Function to check if B is a
# suffix of A or not
def checkSuffix(A, B):
 
    # Convert numbers into strings
    s1 = str(A);
    s2 = str(B);
 
    # Find the lengths of strings
    # s1 and s2
    n1 = len(s1)
    n2 = len(s2)
 
    # Base Case
    if (n1 < n2):
        return False;
     
    # Traverse the strings s1 & s2
    for i in range(n2):
 
        # If at any index characters
        # are unequals then return false
        if (s1[n1 - i - 1] != s2[n2 - i - 1]):
            return False;
             
    # Return true
    return True;
     
# Driver Code
 
# Given numbers
A = 12345
B = 45;
 
# Function Call
result = checkSuffix(A, B);
 
# If B is a suffix of A, then
# print "Yes"
if (result):
    print("Yes")
else:
    print("No")
 
# This code is contributed by grand_master   


C#




// C# program for the above approach
using System;
class GFG{
     
// Function to check if B
// is a suffix of A or not
public static bool checkSuffix(int A,
                               int B)
{
     
    // Convert numbers into strings
    string s1 = A.ToString();
    string s2 = B.ToString();
     
    // Find the lengths of strings
    // s1 and s2
    int n1 = s1.Length;
    int n2 = s2.Length;
     
    // Base case
    if (n1 < n2)
    {
        return false;
    }
     
    // Traverse the strings s1 & s2
    for(int i = 0; i < n2; i++)
    {
         
        // If at any index characters
        // are unequals then return false
        if (s1[n1 - i - 1] !=  s2[n2 - i - 1])
        {
            return false;
        }
    }
     
    // Return true
    return true;
}
 
// Driver code
public static void Main(string[] args)
{
         
    // Given numbers
    int A = 12345, B = 45;
     
    // Function Call
    bool result = checkSuffix(A, B);
     
    // If B is a suffix of A,
    // then print "Yes"
    if (result)
    {
        Console.Write("Yes");
    }
    else
    {
        Console.Write("No");
    }
}
}
 
// This code is contributed by rutvik_56


Javascript




<script>
 
// javascript program for the above approach
 
       
// Function to check if B
// is a suffix of A or not
 
    function checkSuffix( A, B)
{
       
    // Convert numbers into strings
    var s1 = A.toString();
    var s2 = B.toString();
       
    // Find the lengths of strings
    // s1 and s2
     
    var n1 = s1.length;
    var n2 = s2.length;
       
    // Base case
    if (n1 < n2)
    {
        return false;
    }
       
    // Traverse the strings s1 & s2
    for(var i = 0; i < n2; i++)
    {
           
        // If at any index characters
        // are unequals then return false
        if (s1[n1 - i - 1] !=  s2[n2 - i - 1])
        {
            return false;
        }
    }
       
    // Return true
    return true;
}
   
// Driver code
 
           
    // Given numbers
    var A = 12345, B = 45;
       
    // Function Call
    var result = checkSuffix(A, B);
       
    // If B is a suffix of A,
    // then print "Yes"
    if (result)
    {
        document.write("Yes");
    }
    else
    {
        document.write("No");
    }
     
</script>
 
 
  


Output: 

Yes

 

Method 2: Using inbuilt function std::boost::algorithm::ends_with() which is included in Boost Library of C++ which is used to check whether any string contains suffix of another string or not.
Below is the implementation of the above approach:
 

C++




// C++ program for the above approach
#include <bits/stdc++.h>
#include <boost/algorithm/string.hpp>
using namespace std;
 
// Function to check if B is a
// suffix of A or not
void checkSuffix(int A, int B)
{
 
    // Convert numbers into strings
    string s1 = to_string(A);
    string s2 = to_string(B);
 
    bool result;
 
    // Check if s2 is a suffix of s1
    // or not using ends_with() function
    result = boost::algorithm::ends_with(s1,
                                         s2);
 
    // If result is true, print "Yes"
    if (result) {
        cout << "Yes";
    }
    else {
        cout << "No";
    }
}
 
// Driver Code
int main()
{
    // Given numbers
    int A = 12345, B = 45;
 
    // Function Call
    checkSuffix(A, B);
    return 0;
}


Java




// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to check if B is a
// suffix of A or not
static void checkSuffix(int A, int B)
{
 
    // Convert numbers into Strings
    String s1 = String.valueOf(A);
    String s2 = String.valueOf(B);
 
    boolean result;
 
    // Check if s2 is a suffix of s1
    // or not
    result = s1.endsWith(s2);
 
    // If result is true, print "Yes"
    if (result)
    {
        System.out.print("Yes");
    }
    else
    {
        System.out.print("No");
    }
}
 
// Driver Code
public static void main(String[] args)
{
    // Given numbers
    int A = 12345, B = 45;
 
    // Function Call
    checkSuffix(A, B);
}
}
 
// This code is contributed by 29AjayKumar


Python3




# Python3 program for the above approach
 
# Function to check if B is
# a suffix of A or not
def checkSuffix(A, B):
 
    # Convert numbers into strings
    s1 = str(A)
    s2 = str(B)
 
    # Check if s2 is a suffix of s1
    # or not
    result = s1.endswith(s2)
 
    # If result is true print "Yes"
    if (result):
        print("Yes")
    else:
        print("No")
 
# Driver code
if __name__ == '__main__':
 
    # Given numbers
    A = 12345
    B = 45
 
    # Function call
    checkSuffix(A, B)
 
# This code is contributed by himanshu77


C#




// C# program for the above approach
using System;
 
class GFG{
 
// Function to check if B is a
// suffix of A or not
static void checkSuffix(int A, int B)
{
 
    // Convert numbers into Strings
    String s1 = String.Join("", A);
    String s2 = String.Join("", B);
 
    bool result;
 
    // Check if s2 is a suffix of s1
    // or not
    result = s1.EndsWith(s2);
 
    // If result is true, print "Yes"
    if (result)
    {
        Console.Write("Yes");
    }
    else
    {
        Console.Write("No");
    }
}
 
// Driver Code
public static void Main(String[] args)
{
    // Given numbers
    int A = 12345, B = 45;
 
    // Function Call
    checkSuffix(A, B);
}
}
 
// This code is contributed by 29AjayKumar


Javascript




<script>
 
// JavaScript program for the above approach
 
// Function to check if B is a
// suffix of A or not
function checkSuffix( A, B)
{
 
    // Convert numbers into Strings
    let s1 = A.toString();
    let s2 = B.toString();
 
    let result;
 
    // Check if s2 is a suffix of s1
    // or not
    result = s1.endsWith(s2);
 
    // If result is true, print "Yes"
    if (result)
    {
        document.write("Yes");
    }
    else
    {
        document.write("No");
    }
}
 
// Driver Code
 
    // Given numbers
    let A = 12345, B = 45;
 
    // Function Call
    checkSuffix(A, B);
             
</script>


Output: 

Yes

 

Method 3: 

  1. Subtract B from A.
  2. Find the number of digits in B(say X) by using the Method 3 discussed in this article.
  3. Check whether A ends with atleast X number zeros or not. If yes then print “Yes”.
  4. Else print “No”.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if B is a suffix of A or not
bool checkSuffix(int A, int B){
      // Find the number of digit in B
    int digit_B = log10(B) + 1;
 
    // Subtract B from A
    A -= B;
 
    // Returns true, if B is a suffix of A
    return (A % int(pow(10, digit_B)));
}
 
// Driver Code to test above function
int main(){
    // Given numbers
    int A = 12345, B = 45;
 
    // Function Call
    bool result = checkSuffix(A, B);
 
    // If B is a suffix of A, then print "Yes"
    if (!result) cout<<"Yes";
    else cout<<"No";
    return 0;
}


Java




// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to check if B
// is a suffix of A or not
static boolean checkSuffix(int A, int B)
{
 
    // Find the number of digit in B
    int digit_B = (int) (Math.log10(B) + 1);
 
    // Subtract B from A
    A -= B;
 
    // Returns true,
    // if B is a suffix of A
    return (A % (int)(Math.pow(10, digit_B)) > 0);
}
 
// Driver code
public static void main(String[] args)
{
 
    // Given numbers
    int A = 12345, B = 45;
 
    // Function call
    boolean result = checkSuffix(A, B);
 
    // If B is a suffix of A,
    // then print "Yes"
    if (!result)
    {
        System.out.print("Yes");
    }
    else
    {
        System.out.print("No");
    }
}
}
 
// This code is contributed by 29AjayKumar


Python3




# Python3 program for the above approach
import math
 
# Function to check if B is a
# suffix of A or not
def checkSuffix(A, B):
 
    # Find the number of digit in B
    digit_B = int(math.log10(B)) + 1;
 
    # Subtract B from A
    A -= B;
 
    # Returns true,
    # if B is a suffix of A
    return (A % int(math.pow(10, digit_B)));
 
# Driver Code
 
# Given numbers
A = 12345; B = 45;
 
# Function Call
result = checkSuffix(A, B);
 
# If B is a suffix of A, then
# print "Yes"
if (result == 0):
    print("Yes");
 
else:
    print("No");
 
# This code is contributed by Nidhi_biet


C#




// C# program for the above approach
using System;
class GFG{
 
// Function to check if B
// is a suffix of A or not
static bool checkSuffix(int A, int B)
{
 
    // Find the number of digit in B
    int digit_B = (int)(Math.Log10(B) + 1);
 
    // Subtract B from A
    A -= B;
 
    // Returns true,
    // if B is a suffix of A
    return (A % (int)(Math.Pow(10, digit_B)) > 0);
}
 
// Driver code
public static void Main()
{
 
    // Given numbers
    int A = 12345, B = 45;
 
    // Function call
    bool result = checkSuffix(A, B);
 
    // If B is a suffix of A,
    // then print "Yes"
    if (!result)
    {
        Console.Write("Yes");
    }
    else
    {
        Console.Write("No");
    }
}
}
 
// This code is contributed by Code_Mech


Javascript




<script>
 
    // JavaScript program for the above approach
     
    // Function to check if B
    // is a suffix of A or not
    function checkSuffix(A, B)
    {
 
        // Find the number of digit in B
        let digit_B = parseInt(Math.log10(B) + 1, 10);
 
        // Subtract B from A
        A -= B;
 
        // Returns true,
        // if B is a suffix of A
        return (A % (Math.pow(10, digit_B)) > 0);
    }
     
    // Given numbers
    let A = 12345, B = 45;
  
    // Function call
    let result = checkSuffix(A, B);
  
    // If B is a suffix of A,
    // then print "Yes"
    if (!result)
    {
        document.write("Yes");
    }
    else
    {
        document.write("No");
    }
     
</script>


Output: 

Yes

 

Time Complexity: O(logn) because it is using inbuilt pow function
Auxiliary Space: O(1) 

Method 4: 

1. In this method, we use the modulo operator to check if the last len(str(B)) digits of A are equal to B. 

2. We do this by computing A % (10**len(str(B))), which gives us the remainder when A is divided by 10**len(str(B)). 

3. If this remainder is equal to B, then A ends with B.

C++




#include <iostream>
#include<math.h>
using namespace std;
 
int main()
{
 
    int A = 12345;
    int B = 45;
 
    if (A % static_cast<int>(pow(10, to_string(B).length())) == B) {
        cout << "Yes" << endl;
    }
    else {
        cout << "No" << endl;
    }
}


Java




import java.lang.Math;
 
public class Main {
  public static void main(String[] args)
  {
    int A = 12345;
    int B = 45;
     
    // check if A mod 10^length of B is
    // equal to B
    if (A % (int)Math.pow(
          10, Integer.toString(B).length()) == B) {
 
      System.out.println("Yes");
    }
    else {
      System.out.println("No");
    }
  }
}


Python3




A = 12345
B = 45
 
if A % (10**len(str(B))) == B:
    print("Yes")
else:
    print("No")


C#




using System;
 
class Program {
    static void Main(string[] args) {
        int A = 12345;
        int B = 45;
 
        if (A % (int)Math.Pow(10, B.ToString().Length) == B) {
            Console.WriteLine("Yes");
        }
        else {
            Console.WriteLine("No");
        }
    }
}


Javascript




const A = 12345;
const B = 45;
 
if (A % Math.pow(10, B.toString().length) === B) {
    console.log("Yes");
} else {
    console.log("No");
}


Output

Yes

Time Complexity: O(N) 

The time complexity of the code is O(N), where N is the length of A (which is equivalent to the number of digits in A). This is because the code performs two operations that take O(N) time in the worst case:

The expression 10**len(str(B)) calculates the value of 10 raised to the power of the number of digits in B. Since B has at most N digits, the length of str(B) is at most N, and the expression takes O(N) time to compute.
The expression A % (10**len(str(B))) calculates the remainder when A is divided by the value computed in step 1. Since the value computed in step 1 is at most 10**N, the division takes O(N) time to compute.

Space Complexity: O(N) 

The space complexity of the code is also O(N), because the code uses two variables (A and B) that can store numbers with up to N digits.



Similar Reads

Check whether the binary equivalent of a number ends with "001" or not
Given a positive integer N, the task is to check whether the binary equivalent of that integer ends with "001" or not. Print "Yes" if it ends in "001". Otherwise, Print "No". Examples : Input: N = 9 Output: Yes Explanation Binary of 9 = 1001, which ends with 001 Input: N = 5 Output: No Binary of 5 = 101, which does not end in 001 Naive Approach Fin
12 min read
Check whether the binary equivalent of a number ends with given string or not
Given a positive integer N, the task is to check whether the binary equivalent of that integer ends with the given string str or not. Print "Yes" if it ends in "str". Otherwise, Print "No".Examples: Input: N = 23, str = "111"Output: YesExplanation:Binary of 23 = 10111, which ends with "111" Input: N = 5, str = "111"Output: No Approach: The idea is
5 min read
Find if a string starts and ends with another given string
Given a string str and a corner string cs, we need to find out whether the string str starts and ends with the corner string cs or not.Examples: Input : str = "geeksmanishgeeks", cs = "geeks" Output : Yes Input : str = "shreya dhatwalia", cs = "abc" Output : No Algorithm Find length of given string str as well as corner string cs. Let this length b
4 min read
Check if the string has a reversible equal substring at the ends
Given a string S consisting of N characters, the task is to check if this string has a reversible equal substring from the start and the end. If yes, print True and then the longest substring present following the given conditions, otherwise print False. Example: Input: S = "abca"Output: TrueaExplanation:The substring "a" is only the longest substr
5 min read
Check if Triplet exist whose sum ends with digit K
Given an array arr[] of size N, determine if there exist 3 distinct indices integers, such that their sum ends in digit K. Examples: Input: arr[] = {1, 2, 5, 3}, K = 0Output: YESExplanation: 2 + 3 + 5 = 10 i.e., end digit 0. Input: arr[] = {3, 1, 8, 4}, K = 0Output: NO Approach: To solve the problem follow the below idea: Find all possible triplets
10 min read
Check if a number starts with another number or not
Given two numbers A and B where (A &gt; B), the task is to check if B is a prefix of A or not. Print "Yes" if it is a prefix Else print "No". Examples: Input: A = 12345, B = 12 Output: Yes Input: A = 12345, B = 345 Output: No Approach: Convert the given numbers A and B to strings str1 and str2 respectively.Traverse both the strings from the start o
8 min read
Number of strings which starts and ends with same character after rotations
Given a string str, the task is to find the number of strings that start and end with the same character after a rotation at every possible index of the given string. Examples: Input: str = "GeeksforGeeks" Output: 2 Explanation: All possible strings with rotations at every index are: "GeeksforGeeks", "eeksforGeeksG", "eksforGeeksGe", "ksforGeeksGee
4 min read
Minimum number of array elements from either ends required to be subtracted from X to reduce X to 0
Given an array nums[] and an integer X, the task is to reduce X to 0 by removing either the leftmost or the rightmost array elements and subtracting its value from X, minimum number of times. If it's possible to reduce X to 0, print the count of operations required. Otherwise, return -1. Examples: Input: nums[] = {3,2,20,1,1,3}, X = 10Output: 5Expl
9 min read
Create new Mobile Number by selecting maximum from ends after inserting pairwise absolute difference in middle
Given a String ph[], the task is to find the absolute difference of consecutive elements and insert the result in between the consecutive elements. By doing this size of phone numbers will increase from 10 to 19. Now we have to compare digits from first and last and select maximum in this way we will get a new phone number. Examples: Input: ph = "9
8 min read
Check if a circle lies inside another circle or not
Given two circles with radii and centres given. The task is to check whether the smaller circle lies inside the bigger circle or not.  Examples:   Input: x1 = 10, y1 = 8, x2 = 1, y2 = 2, r1 = 30, r2 = 10 Output: The smaller circle lies completely inside the bigger circle without touching each other at a point of circumference. Input :x1 = 7, y1 = 8
6 min read
Article Tags :
Practice Tags :