Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

剑指 Offer 46. 把数字翻译成字符串 #203

Open
Tcdian opened this issue Jun 9, 2020 · 1 comment
Open

剑指 Offer 46. 把数字翻译成字符串 #203

Tcdian opened this issue Jun 9, 2020 · 1 comment

Comments

@Tcdian
Copy link
Owner

Tcdian commented Jun 9, 2020

剑指 Offer 46. 把数字翻译成字符串

给定一个数字,我们按照如下规则把它翻译为字符串:0 翻译成 “a”1 翻译成 “b”,……,11 翻译成 “l”,……,25 翻译成 “z”。一个数字可能有多个翻译。请编程实现一个函数,用来计算一个数字有多少种不同的翻译方法。

Example

输入: 12258
输出: 5
解释: 12258有5种不同的翻译,分别是"bccfi", "bwfi", "bczi", "mcfi"和"mzi"

Note

  • 0 <= num < 231
@Tcdian
Copy link
Owner Author

Tcdian commented Jun 9, 2020

Solution

  • JavaScript Solution
/**
 * @param {number} num
 * @return {number}
 */
var translateNum = function(num) {
    const str = String(num);
    const dp = new Array(str.length + 1);
    for (let i = 0; i <= str.length; i++) {
        if (i <= 1) {
            dp[i] = 1;
            continue;
        } 
        const twoDigits = Number(str.slice(i - 2, i));
        if ( twoDigits <= 25 && twoDigits > 9) {
            dp[i] = dp[i - 1] + dp[i - 2];
        } else {
            dp[i] = dp[i - 1];
        }
    }
    return dp[str.length];
};
  • TypeScript Solution
function translateNum(num: number): number {
    const str = String(num);
    const dp: number[] = new Array(str.length + 1);
    for (let i = 0; i <= str.length; i++) {
        if (i <= 1) {
            dp[i] = 1;
            continue;
        } 
        const twoDigits = Number(str.slice(i - 2, i));
        if ( twoDigits <= 25 && twoDigits > 9) {
            dp[i] = dp[i - 1] + dp[i - 2];
        } else {
            dp[i] = dp[i - 1];
        }
    }
    return dp[str.length];
};

@Tcdian Tcdian changed the title 《剑指 Offer(第 2 版)》46. 把数字翻译成字符串 剑指 Offer 46. 把数字翻译成字符串 Jun 30, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant