306. Additive Number 自己写的,居然ac了,写一遍比看100遍强,看别人对边界的处理纯属浪费时间,不如自己动手,自己手写才能提高

加法数字符串识别
本文介绍了一种算法,用于判断一个由数字组成的字符串是否为加法数。加法数是一种特殊的字符串,其数字序列中每个数字(从第三个开始)都是前两个数字之和。文章详细解释了加法数的概念,并通过实例说明如何确定一个字符串是否符合加法数的标准。

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, 03 or 1, 02, 3 is 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?

Credits:

Special thanks to @jeantimex for adding this problem and creating all test cases.




class Solution {
public:
    bool isAdditiveNumber(string num) {

        for(int i=0;i<num.size()/3+1;i++){
            string s1=num.substr(0,i-0+1);
            long l1=stol(s1);
            string tmp=to_string(l1);
            
            if(s1.size()==tmp.size()){
                for(int j=i+1;j<num.size()/3*2+1;j++){
                    string s2=num.substr(i+1,j-(i+1)+1);
                    long l2=stol(s2);
                    string tmp=to_string(l2);
                    if(s2.size()==tmp.size()){
                        bool sum_flag=false;
                        
                        if(dp(l1,l2,i,j,num,sum_flag))
                            return true;
                    }
                }
            }
                
        }
        return false;
    }
    bool dp(long first,long second,int i,int j,string num,bool sum_flag){
        if(sum_flag==true&&(j==num.size()-1)){
            return true;
        }
        else if(j==num.size()-1){
            return false;
        }
        long ans=first+second;
        string ans_s=to_string(ans);
        int len=ans_s.size();
        if(j+1+len-1>num.size()-1){
            return false;
        }
        string num_sub=num.substr(j+1,len);
        
        if(ans_s==num_sub){
            sum_flag=true;
            return dp(second,ans,j,j+1+len-1,num,sum_flag);
        }
        return false;
        
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值