[LeetCode] Additive Number

简介: Af first I read the title as "Addictive Number". Anyway, this problem can be solved elegantly using recursion.

Af first I read the title as "Addictive Number". Anyway, this problem can be solved elegantly using recursion. This post shares a nice recursive C++ code with handling of the follow-up by implementing string addition function.

The code is rewritten as follows.

 1 class Solution {
 2 public:
 3     bool isAdditiveNumber(string num) {
 4         int n = num.size();
 5         for (int i = 1; i <= n/2; i++)
 6             for (int j = 1; j <= (n-i)/2; j++)
 7                 if (additive(num.substr(0, i), num.substr(i, j), num.substr(i + j)))
 8                     return true;
 9         return false;
10     }
11 private:
12     bool additive(string a, string b, string c) {
13         string s = add(a, b);
14         if (s == c) return true;
15         if (c.size() <= s.size() || s.compare(c.substr(0, s.size())))
16             return false;
17         return additive(b, s, c.substr(s.size()));
18     }
19     string add(string& a, string& b) {
20         string s;
21         int i = a.size() - 1, j = b.size() - 1, c = 0;
22         while (i >= 0 || j >= 0) {
23             int d = (i >= 0 ? (a[i--] - '0') : 0) + (j >= 0 ? (b[j--] - '0') : 0) + c;
24             s += (d % 10 + '0');
25             c = d / 10;
26         }
27         if (c) s += ('0' + c);
28         reverse(s.begin(), s.end());
29         return s;
30     }
31 };

This problem can also be solved iteratively, like peisi's code, which is rewritten in C++ below.

 1 class Solution {
 2 public:
 3     bool isAdditiveNumber(string num) {
 4         int n = num.length();
 5         for (int i = 1; i <= n/2; i++)
 6             for (int j = 1; max(i, j) <= n - i - j; j++)
 7                 if (additive(i, j, num)) return true;
 8         return false;
 9     }
10 private:
11     bool additive(int i, int j, string& num) {
12         if (num[i] == '0' && j > 1) return false;
13         string a = num.substr(0, i);
14         string b = num.substr(i, j);
15         for (int k = i + j; k < num.length(); k += b.length()) {
16             b.swap(a);
17             b = add(a, b);
18             string tail = num.substr(k);
19             if (b.compare(tail.substr(0, b.size()))) return false;
20         }
21         return true;
22     }
23     string add(string& a, string& b) { 
24         string s;
25         int i = a.size() - 1, j = b.size() - 1, c = 0;
26         while (i >= 0 || j >= 0) {
27             int d = (i >= 0 ? (a[i--] - '0') : 0) + (j >= 0 ? (b[j--] - '0') : 0) + c;
28             s += (d % 10 + '0');
29             c = d / 10;
30         }
31         if (c) s += ('0' + c);
32         reverse(s.begin(), s.end());
33         return s;
34     }
35 };

If you are a Pythoner, you may also love Stefan's code, which is pasted below.

 1 def isAdditiveNumber(self, num):
 2     n = len(num)
 3     for i, j in itertools.combinations(range(1, n), 2):
 4         a, b = num[:i], num[i:j]
 5         if b != str(int(b)):
 6             continue
 7         while j < n:
 8             c = str(int(a) + int(b))
 9             if not num.startswith(c, j):
10                 break
11             j += len(c)
12             a, b = b, c
13         if j == n:
14             return True
15     return False

 

目录
相关文章
|
算法
Leetcode 313. Super Ugly Number
题目翻译成中文是『超级丑数』,啥叫丑数?丑数就是素因子只有2,3,5的数,7 14 21不是丑数,因为他们都有7这个素数。 这里的超级丑数只是对丑数的一个扩展,超级丑数的素因子不再仅限于2 3 5,而是由题目给定一个素数数组。与朴素丑数算法相比,只是将素因子变了而已,解法还是和朴素丑数一致的。
99 1
|
5月前
|
存储 SQL 算法
LeetCode 题目 65:有效数字(Valid Number)【python】
LeetCode 题目 65:有效数字(Valid Number)【python】
|
6月前
|
存储 算法
【LeetCode力扣】单调栈解决Next Greater Number(下一个更大值)问题
【LeetCode力扣】单调栈解决Next Greater Number(下一个更大值)问题
45 0
|
存储
Leetcode Single Number II (面试题推荐)
给你一个整数数组,每个元素出现了三次,但只有一个元素出现了一次,让你找出这个数,要求线性的时间复杂度,不使用额外空间。
39 0
LeetCode contest 190 5417. 定长子串中元音的最大数目 Maximum Number of Vowels in a Substring of Given Length
LeetCode contest 190 5417. 定长子串中元音的最大数目 Maximum Number of Vowels in a Substring of Given Length
LeetCode Contest 178-1365. 有多少小于当前数字的数字 How Many Numbers Are Smaller Than the Current Number
LeetCode Contest 178-1365. 有多少小于当前数字的数字 How Many Numbers Are Smaller Than the Current Number
LeetCode 136. 只出现一次的数字 Single Number
LeetCode 136. 只出现一次的数字 Single Number
LeetCode contest 177 5169. 日期之间隔几天 Number of Days Between Two Dates
LeetCode contest 177 5169. 日期之间隔几天 Number of Days Between Two Dates
|
2月前
|
Unix Shell Linux
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行
本文提供了几个Linux shell脚本编程问题的解决方案,包括转置文件内容、统计词频、验证有效电话号码和提取文件的第十行,每个问题都给出了至少一种实现方法。
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行
|
3月前
|
搜索推荐 索引 Python
【Leetcode刷题Python】牛客. 数组中未出现的最小正整数
本文介绍了牛客网题目"数组中未出现的最小正整数"的解法,提供了一种满足O(n)时间复杂度和O(1)空间复杂度要求的原地排序算法,并给出了Python实现代码。
113 2