LeetCode 306 Additive Number

本文介绍了一种通过遍历字符串并验证子串是否形成有效的加性数序列的方法。加性数是指一个字符串,其数字可以构成至少三个数的序列,且从第三个数开始,每个数都是前两个数之和。文章提供了两种实现方案,并讨论了如何避免溢出问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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?

这道题目,没有找到更喜欢的做法,所以brute force暴力解决。

	public boolean isAdditiveNumber(String num) {
		int len = num.length();
		for (int i = 1; i <= len / 2; i++) {
			for (int j = 1; Math.max(i, j) <= len - j - i; j++) {
				String s1 = num.substring(0, i), s2 = num.substring(i, j + i);
				if (s1.charAt(0) == '0' && s1.length() > 1 || s2.charAt(0) == '0' && s2.length() > 1)
					continue;
				Long d1 = new Long(s1), d2 = new Long(s2), sum = d1 + d2;
				String next = sum.toString(), now = s1 + s2 + next;
				while (now.length() < len && num.startsWith(now)) {
					d1 = d2;
					d2 = sum;
					sum = d1 + d2;
					now += sum.toString();
				}
				if (now.equals(num)) return true;
			}
		}
		return false;
	}


再贴一个看着稍微顺眼的写法吧,比上面的快了1ms。感谢此博客

	public boolean isAdditiveNumber2(String num) {
		for (int i = 1; i <= num.length() / 2; i++)
			for (int j = 1; Math.max(i, j) <= num.length() - j - i; j++)
				if (isValid(num, num.substring(0, i), num.substring(i, i + j), i + j)) return true;
		return false;
	}

	private boolean isValid(String num, String first, String second, int index) {
		if (first.length() > 1 && first.startsWith("0")
				|| second.length() > 1 && second.startsWith("0")) return false;
		if (index == num.length()) return true;
		long sum = Long.parseLong(first) + Long.parseLong(second);
		if (num.startsWith(sum + "", index))
			if (isValid(num, second, sum + "", index + (sum + "").length())) return true;
		return false;
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值