C++Server Side ProgrammingProgramming

Suppose we have a string containing only digits through '0' to '9', we have to write a function to determine whether it's an additive number or not. The additive number is a string whose digits can form additive sequence. A valid additive sequence should contain at least three numbers. Here except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two. So if the input is like “112358”, then the answer will be true, as 2 = 1 + 1, 3 = 1 + 2, 5 = 2 + 3, 8 = 3 + 5.

To solve this, we will follow these steps −

• Define a method called ok(), this will take s, index, prev1, prev2

• if index >= size of s, then return true

• req := prev1 + prev2 and num := req as string

• x := one blank string

• for i in range index to size of s

• x := x + s[i]

• if x = num, and ok(s, i + 1, prev2, x as integer), then return true

• return false

• From the main method do the following −

• n := size of num

• for i in range 1 to n – 2

• for j in range 1 to i

• s1 := substring of num from 0 to j – 1

• s2 := substring of num from j to i – j

• x := max of s1 size and s2 size

• if x > n – i, then go for the next iteration

• if (s1 is 0 and size of s1 > 0) OR (s2 is 0 and size of s2 > 1), then skip to the next iteration

• if ok(num, i + 1, s1 as integer and s2 as integer) is true, then return true

• return false

## Example(C++)

Let us see the following implementation to get better understanding −

Live Demo

#include <bits/stdc++.h>
using namespace std;
typedef long long int lli;
class Solution {
public:
bool ok(string s, int idx, lli prev1, lli prev2){
if(idx >= s.size()) return true;
lli req = prev1 + prev2;
string num = to_string(req);
string x = "";
for(int i = idx; i < s.size(); i++){
x += s[i];
if(x == num && ok(s, i + 1, prev2, stol(x))) return true;
}
return false;
}
int n = num.size();
for(int i = 1; i < n - 1; i++){
for(int j = 1; j <= i; j++){
string s1 = num.substr(0, j);
string s2 = num.substr(j, i - j + 1);
int x = max((int)s1.size(), (int)s2.size());
if(x > n - i) continue;
if((s1 == '0' && s1.size() > 1) || (s2 == '0' && s2.size() > 1)) continue;
if(ok(num, i + 1, stol(s1), stol(s2))) return true;
}
}
return false;
}
};
main(){
Solution ob;
}
"112358"
1