Check if a numeric string can be split into substrings having difference between consecutive numbers equal to K | C ++ program for the above approach ; Function to check if a numeric string can be split into substrings such that the difference between the consecutive substrings is K ; Stores the size of the string ; Iterate over the range [ 1 , N ] and try each possible starting number ; Convert the number to string ; Build up a sequence starting with the number ; Compare it with the original string s ; Print the result ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void isPossible ( string s , int K ) { bool valid = false ; long firstx = -1 ; int n = s . length ( ) ; for ( int i = 1 ; i <= n / 2 ; ++ i ) { long x = stol ( s . substr ( 0 , i ) ) ; firstx = x ; string test = to_string ( x ) ; while ( test . length ( ) < s . length ( ) ) { x -= K ; test += to_string ( x ) ; } if ( test == s ) { valid = true ; break ; } } cout << ( ( valid == true ) ? " Yes ▁ " : " No " ) ; } int main ( ) { string S = "8642" ; int K = 2 ; isPossible ( S , K ) ; return 0 ; }