1. 程式人生 > >LeetCode(306) Additive Number

LeetCode(306) 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.

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.

分析

給定一個字串,題目要求判斷該字串是否為約束規則下的可加字串。

手動判斷很容易,但是轉為程式實現開始不知從何入手。

查閱一些資料,最終搞定。詳見程式碼。

AC程式碼

class Solution {
public:
    bool isAdditiveNumber(string num) {
        if (num.empty())
            return false;

        int len = num.size();
        for (int i = 1; i < len - 1; ++i)
        {
            string
a = num.substr(0, i); //非首個以0開頭的加數違反規則 if (a[0] == '0' && i > 1) continue; for (int j = 1; j < len; ++j) { string b = num.substr(i, j); if (b[0] == 0 && j > 1) continue; string ret = add(a, b); if (i + j + ret.length() > len) continue; //儲存原字串中和上一和 同樣長度的子串 string val = num.substr(i + j, ret.length()); //當前已經相加的末尾下標 int pass = i + j; string tmp; while (ret == val) { //判斷是否到字串末尾 pass += val.length(); if (len == pass) return true; tmp = b; b = ret; //下一步驟加法實現 ret = add(tmp, b); val = num.substr(pass, ret.length()); }//while }//for }//for return false; } //字串加法實現 string add(string a, string b) { int len_a = a.size(), len_b = b.size(); string ret = ""; int i = len_a - 1, j = len_b - 1, carry = 0; while (i>=0 && j>=0) { int tmp = a[i] + b[j] - 2 * '0' + carry; carry = tmp / 10; char c = tmp % 10 + '0'; ret += c; --i; --j; }//while while (i >= 0) { int tmp = a[i] - '0' + carry; carry = tmp / 10; char c = tmp % 10 + '0'; ret += c; --i; }//while while (j >= 0) { int tmp = b[j] - '0' + carry; carry = tmp / 10; char c = tmp % 10 + '0'; ret += c; --j; }//while if (carry != 0) ret += carry + '0'; reverse(ret.begin(), ret.end()); return ret; } };