LeetCode306. Additive Number

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.

Given a string containing only digits '0'-'9', write a function to determine if it's an additive number.

Note: Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, 03 or 1, 02, 3 is invalid.

Example 1:

Input: "112358"
Output: true 
Explanation: 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

Example 2:

Input: "199100199"
Output: true 
Explanation: The additive sequence is: 1, 99, 100, 199. 
             1 + 99 = 100, 99 + 100 = 199

Follow up:
How would you handle overflow for very large input integers?

这道题是典型的穷举,但是需要注意题目最后的要求:如何处理非常大的数。因为我们要使用加法,如果加数超出了整型能够表示的范围,那么就有可能出错,所以我这里使用了自己实现的字符串加法,这样不管多大的数都可以处理了。

class Solution {
public:
	bool isAdditiveNumber(string num) {
		for (int i = 1; i <= num.size() - i; i++) {
            if (num[0] == '0' && i > 1) continue;
			for (int j = 1; j <= num.size() - i - j; j++) {
				if (num[i] == '0' && j > 1) continue;
				string strA(num.begin(), num.begin() + i);
				string strB(num.begin() + i, num.begin() + i + j);
				string s(num.begin() + i + j, num.end());
				if (helper(strA, strB, s)) return true;
			}
		}
		return false;
	}

private:
	bool helper(string strA, string strB, string s) {
		if (s[0] == '0' && s.size() > 1) return false;

		int len = max(strB.size(), strA.size());

		while (len <= s.size() && len <= max(strA.size(), strB.size()) + 1) {
			string strC = s.substr(0, len);
			if (strC == addStr(strA, strB)) {
				if (len == s.size()) return true;
				string strS = s.substr(len);
				return helper(strB, strC, strS);
			}
			len++;
		}
		return false;
	}
	string addStr(string a, string b) {
		int flag = 0;
		string res = "";

		reverse(a.begin(), a.end());
		reverse(b.begin(), b.end());
		int maxLen = max(a.size(), b.size());
		
		for (int i = 0; i < maxLen; i++) {
			int sum = flag;
			if (i < a.size()) sum += a[i] - '0';
			if (i < b.size()) sum += b[i] - '0';
			flag = sum / 10;
			sum %= 10;
			res = to_string(sum) + res;
		}
		if (flag == 1) res = "1" + res;
		return res;
	}
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值