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. Unity开发游戏 flapybird 无广告老马版分享

    Flapybird确实是一款非常好玩的游戏,但是上手难度比较大.经过老马模仿加工,把游戏难度降低,而且不加入任何广告. 特此分享.下载地址:http://files.cnblogs.com/fly_d ...

  2. Msbuild利用cpu多核加速

    msbuild /t:Rebuild /p:Configuration=Release /m /m 自动检测cpu数量启动对应数量进程

  3. 仿IOS 开关按钮

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  4. Linux初学 - 安装及网络配置

    安装版本 CentOS-6.4 虚拟机  vmware workstation 12 配置 网络配置 检查网络设置是否成功 如果网络配置文件检查没有问题,配置完成后网络仍然ping不同 1.检查虚拟机 ...

  5. Proxy模式:管理第三方API

    软件中的Barrier. 数据从程序移到DB中时,要跨越数据库的Barrier.消息从一个PC到另一个PC时,要跨越网络Barrier. 跨越可能是复杂的,很可能处理Barrier的Code会多于处理 ...

  6. Python之线程池

    版本一: #!/usr/bin/env python # -*- coding:utf-8 -*- import Queue import threading class ThreadPool(obj ...

  7. 适合于小团队产品迭代的APP测试流程

    一.测试周期 测试周期一般为2~3天,根据项目情况以及版本质量可适当缩短或延长测试时间.正式测试前先向主管或产品经理确认项目排期. 二.测试资源 测试任务开始前,检查各项测试资源. 产品功能需求文档. ...

  8. 如何实现在H5里调起高德地图APP?(下)

    这一篇文章将告诉您,如果直接打开高德地图APP,并展示路线规划.适合有定位的移动设备,可以查询到从“我的位置”到目的地的路径规划,并直接导航. 场景二.调起高德地图的路线规划功能 导航是目前JSAPI ...

  9. android如何播放和录制音频

    视频录制功能正在走来,在Androidsdk中有与之相关的类:android.media.MediaRecorder.当然,因为模拟器上没有提供必要的硬件设施,所以在学习过程中并不能实现.Media能 ...

  10. old header

    海纳百川 山不拒土 No Backspace in Real Life. Love Life![Cloud][LBS][GIS][GPS][MAPS][C++][Java]