Additive Number
2015-11-19 18:07
253 查看
Additive number is a positive integer 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:
also an additive number, the additive sequence is:
Note: Numbers in the additive sequence cannot have leading zeros, so sequence
Given a string represents an integer, write a function to determine if it's an additive number.
Follow up:
How would you handle overflow for very large input integers?
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 represents an integer, 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.size(); for(int i=1;i<=len/2;i++){ for(int j=1;j<=(len-i)/2;j++){ string str1=num.substr(0,i); string str2=num.substr(i,j); if(check2(str1,str2,num.substr(i+j))) return true; } } return false; } bool check(string str1,string str2,string num){ string sum=add(str1,str2); int n3=sum.size(); if(sum==num) return true; if(n3>=num.size()||sum!=num.substr(0,n3)) return false; else return check(str2,sum,num.substr(n3)); } bool check2(string str1,string str2,string num){ string sum=add(str1,str2); while(true){ if(sum==num) return true; if(sum.size()>=num.size()||sum!=num.substr(0,sum.size())) return false; num=num.substr(sum.size()); str1=str2;str2=sum; sum=add(str1,str2); } } string add(string str1,string str2){ int i1=str1.size()-1; int i2=str2.size()-1; int carry=0; string res; while(i1>=0||i2>=0){ int sum=(i1>=0?str1[i1]-'0':0)+(i2>=0?str2[i2]-'0':0)+carry; carry=sum/10; res.push_back(sum%10+'0'); i1--;i2--; } if(carry) res.push_back(carry+'0'); reverse(res.begin(),res.end()); return res; } };
相关文章推荐
- js 数组包含
- jQuery 操作复选框(checkbox) attr checked不起作用
- iOS自定义tabBar手势侧滑返回(仿系统)
- JSONModel解析数据成Model
- C# 反射性能比较
- Hibernate的批量处理
- 动画状态机控制单个动画片段播放速度
- apple watch 开发关键知识点
- python中生成二维码图片
- 死锁查看处理(二)
- Swift用CoreMotion得到屏幕当前方向的方法
- python 备份脚本
- iOS打包成.a静态库
- Query-1.9.1源码分析系列(十) 事件系统——事件委托
- navigation 系统自带交互手势
- 斐波那契数列 求第n个数、前n个数之和
- shell脚本:ip/mask 转换为 ip1-ip2
- cygwin:自制离线安装备份包
- UICollectionView (仿系统相册,按日期分区 item瀑布流)
- Sql Server 获取指定表、视图结构