给定一个数字,我们按照如下规则把它翻译为字符串:0 翻译成 “a” ,1 翻译成 “b”,……,11 翻译成 “l”,……,25 翻译成 “z”。一个数字可能有多个翻译。请编程实现一个函数,用来计算一个数字有多少种不同的翻译方法。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/ba-shu-zi-fan-yi-cheng-zi-fu-chuan-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
import java.util.Scanner;
class Solution {
public int translateNum(int num) {
char[] str = String.valueOf(num).toCharArray();
int a = 1, b = 1, c;
for (int i = 0; i < str.length; ++i) {
c = b;
if (i > 0 && str[i - 1] == '1') {
c += a;
}
if (i > 0 && str[i - 1] == '2' && str[i] <= '5') {
c += a;
}
a = b;
b = c;
}
return b;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
System.out.println(new Solution().translateNum(in.nextInt()));
}
}
}
知识兔 心之所向,素履以往 生如逆旅,一苇以航