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.

 class Solution {
public:
bool isAdditiveNumber(string num) {
int n = num.size();
for (int i = ; i <= n/; i++)
for (int j = ; j <= (n-i)/; j++)
if (additive(num.substr(, i), num.substr(i, j), num.substr(i + j)))
return true;
return false;
}
private:
bool additive(string a, string b, string c) {
string s = add(a, b);
if (s == c) return true;
if (c.size() <= s.size() || s.compare(c.substr(, s.size())))
return false;
return additive(b, s, c.substr(s.size()));
}
string add(string& a, string& b) {
string s;
int i = a.size() - , j = b.size() - , c = ;
while (i >= || j >= ) {
int d = (i >= ? (a[i--] - '') : ) + (j >= ? (b[j--] - '') : ) + c;
s += (d % + '');
c = d / ;
}
if (c) s += ('' + c);
reverse(s.begin(), s.end());
return s;
}
};

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

 class Solution {
public:
bool isAdditiveNumber(string num) {
int n = num.length();
for (int i = ; i <= n/; i++)
for (int j = ; max(i, j) <= n - i - j; j++)
if (additive(i, j, num)) return true;
return false;
}
private:
bool additive(int i, int j, string& num) {
if (num[i] == '' && j > ) return false;
string a = num.substr(, i);
string b = num.substr(i, j);
for (int k = i + j; k < num.length(); k += b.length()) {
b.swap(a);
b = add(a, b);
string tail = num.substr(k);
if (b.compare(tail.substr(, b.size()))) return false;
}
return true;
}
string add(string& a, string& b) {
string s;
int i = a.size() - , j = b.size() - , c = ;
while (i >= || j >= ) {
int d = (i >= ? (a[i--] - '') : ) + (j >= ? (b[j--] - '') : ) + c;
s += (d % + '');
c = d / ;
}
if (c) s += ('' + c);
reverse(s.begin(), s.end());
return s;
}
};

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

 def isAdditiveNumber(self, num):
n = len(num)
for i, j in itertools.combinations(range(1, n), 2):
a, b = num[:i], num[i:j]
if b != str(int(b)):
continue
while j < n:
c = str(int(a) + int(b))
if not num.startswith(c, j):
break
j += len(c)
a, b = b, c
if j == n:
return True
return False

[LeetCode] Additive Number的更多相关文章

  1. [LeetCode] Additive Number 加法数

    Additive number is a positive integer whose digits can form additive sequence. A valid additive sequ ...

  2. 【LeetCode】306. Additive Number 解题报告(Python)

    [LeetCode]306. Additive Number 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http: ...

  3. Leetcode 306. Additive Number

    Additive number is a string whose digits can form additive sequence. A valid additive sequence shoul ...

  4. [LeetCode] 306. Additive Number [Medium]

    306. Additive Number class Solution { private: string stringAddition(string &a, string &b) { ...

  5. 【LeetCode】306. Additive Number

    题目: Additive number is a string whose digits can form additive sequence. A valid additive sequence s ...

  6. LeetCode(306) Additive Number

    题目 Additive number is a string whose digits can form additive sequence. A valid additive sequence sh ...

  7. 【刷题-LeetCode】306. Additive Number

    Additive Number Additive number is a string whose digits can form additive sequence. A valid additiv ...

  8. 306. Additive Number

    题目: Additive number is a string whose digits can form additive sequence. A valid additive sequence s ...

  9. [Swift]LeetCode306. 累加数 | Additive Number

    Additive number is a string whose digits can form additive sequence. A valid additive sequence shoul ...

随机推荐

  1. TypeScript的全部资料,以后都放这儿了

    很早之前就听说TypeScript了(以下简称TS),但总是用难以抽出时间给自己找到这个冠冕堂皇的理由.最近又心血来潮,打算写TS的博客了,毕竟TS核心开发者也是C#之父,像我这么热爱C#的人,怎么可 ...

  2. 微软BI 之SSIS 系列 - 在 SSIS 中导入 ACCESS 数据库中的数据

    开篇介绍 来自 天善学院 一个学员的问题,如何在 SSIS 中导入 ACCESS 数据表中的数据. 在 SSIS 中导入 ACCESS 数据库数据 ACCESS 实际上是一个轻量级的桌面数据库,直接使 ...

  3. p4 是否能自动merge

      总结: 1)如果在copy merge(-at)/auto merge(-am)后修改source branch,则可以自动被copy merge: 2)如果在manual merge后修改sou ...

  4. dubbo配置文件报错解决思路

    导入dubbo项目到Eclipse,配置文件报了如下异常: Multiple annotations found at this line: - cvc-complex-type.2.4.c: The ...

  5. paip.hibernate list 返回位null的解决

    paip.hibernate list 返回位null的解决 但是size是对的... 里面都是null... hb3.2版本...oracle11g =========原因:没主键 也许没主键,看累 ...

  6. Qt for Android 打包 SQLite 数据库

    Qt for Android 调用 SQLite 数据库时, 怎样将已经存在的数据库附加到 APK 中? 直接在你项目里面的Android源码的根目录下新建一个文件夹assets, 数据库就可以放里面 ...

  7. JQ中 trigger()和triggerHandler()区别

    既然使用了trigger和triggerHandler,那么你应该了解了他们的差别了. trigger():在每一个匹配的元素上触发某类事件. triggerHandler():这个特别的方法将会触发 ...

  8. textViewDidChange: crashes in iOS 7

    What's happening is that you're typing what is referred to as multistage text input, i.e. the input ...

  9. nginx用户认证配置( Basic HTTP authentication)

    ngx_http_auth_basic_module模块实现让访问着,只有输入正确的用户密码才允许访问web内容.web上的一些内容不想被其他人知道,但是又想让部分人看到.nginx的http aut ...

  10. 一道SQL面试例题 if...else 与聚集函数

    晚上回来,同学说面试遇到了一个SQL面试题目,自己做了一下,总结总结. 题目如下: 下面是产品数据表(产品id,颜色col,数量num),其中每种产品有1~2种颜色. 求每种产品各颜色的数量差值(对于 ...