题目描述:
现有一串神秘的密文 ciphertext
,经调查,密文的特点和规则如下:
- 密文由非负整数组成
- 数字 0-25 分别对应字母 a-z
请根据上述规则将密文 ciphertext
解密为字母,并返回共有多少种解密结果。
示例 1:
输入:ciphertext = 216612 输出:6 解释:216612 解密后有 6 种不同的形式,分别是 "cbggbc","vggbc","vggm","cbggm","cqgbc" 和 "cqgm"
题解:
解法一:
将int类型转成字符串
class Solution {
public int crackNumber(int ciphertext) {
String s = String.valueOf(ciphertext);
int a = 1, b = 1, c = 1;
int p = s.charAt(0) - '0';
for (int i = 1; i < s.length(); i++) {
int num = s.charAt(i) - '0';
c = a;
if (p == 2 && num <= 5 || p == 1) {
c += b;
}
p = num;
b = a;
a = c;
}
return c;
}
}
解法二:
class Solution {
public int crackNumber(int ciphertext) {
int a = 1, b = 1;
int p = ciphertext % 10;
ciphertext /= 10;
while (ciphertext != 0) {
int num = ciphertext % 10;
ciphertext /= 10;
int c = a;
if (num == 1 || num == 2 && p <= 5) {
c += b;
}
b = a;
a = c;
p = num;
}
return a;
}
}