LeetCode *** 306. Additive Number
2016-04-23 14:47
274 查看
题目:
Additive number is a string whose digits can form additive sequence.
A valid additive sequence should contain at least three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two.
For example:
Note: Numbers in the additive sequence cannot have leading zeros, so sequence
Given a string containing only digits
Follow up:
How would you handle overflow for very large input integers?
分析:
回溯。
代码:
Additive number is a string whose digits can form additive sequence.
A valid additive sequence should contain at least three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two.
For example:
"112358"is an additive number because the digits can form an additive sequence:
1, 1, 2, 3, 5, 8.
1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8
"199100199"is also an additive number, the additive sequence is:
1, 99, 100, 199.
1 + 99 = 100, 99 + 100 = 199
Note: Numbers in the additive sequence cannot have leading zeros, so sequence
1, 2, 03or
1, 02, 3is invalid.
Given a string containing only digits
'0'-'9', write a function to determine if it's an additive number.
Follow up:
How would you handle overflow for very large input integers?
分析:
回溯。
代码:
class Solution { public: bool isAdditiveNumber(string num) { int len=num.length(); for(int i=1;i<=len/2;++i) for(int j=1;j<=(len-i)/2;++j){ if(check(num.substr(0,i),num.substr(i,j),num.substr(i+j))) return true; } return false; } bool check(string add,string added,string result){ if(result=="")return true; if(added.length()>1&&added[0]=='0')return false; string res=""; int lena=add.length()-1,lenad=added.length()-1; int flag=0,t; while(lena>=0||lenad>=0){ t=0; if(lena>=0){ t+=add[lena]-'0'; --lena; } if(lenad>=0){ t+=added[lenad]-'0'; --lenad; } t+=flag; flag=t/10; t=t%10; res.insert(res.begin(),t+'0'); } if(flag)res.insert(res.begin(),flag+'0'); if(res.length()>result.length())return false; int len=res.length(),pos=0; while(pos<len){ if(res[pos]!=result[pos])return false; pos++; } return check(added,result.substr(0,len),result.substr(len)); } };
相关文章推荐
- Qt实现基于G.729A(G729A)的语音聊天
- 处理mysqldump导出文件案例之文件大小为0
- 2016SDAU编程练习二1010
- shape标签总结
- 简易通讯录
- windows上安装RabbitMQ
- PHP加速器eaccelerator导致php-fpm进程卡死原因分析
- Exercise(5):最大子矩阵
- Linux字符设备注册与注销
- 正则
- 216. Combination Sum III
- 209. Minimum Size Subarray Sum
- java jsp实现网站访问量的统计
- SAR成像基础知识急救箱(零)关于傅里叶变换的几个小困惑
- Android源码分析之——下载并编译源码
- 写出ELGamal公钥密码算法的加密、解密过程
- Docker基础技术:DeviceMapper
- Android之Viewpager+Fragment实现懒加载
- HDU 5670 Machine
- 数据结构—约瑟夫问题