|
| 1 | +# 题目描述(简单难度) |
| 2 | + |
| 3 | + |
| 4 | + |
| 5 | +根据对应规则,将字符串转为对应的数字。 |
| 6 | + |
| 7 | +# 解法一 |
| 8 | + |
| 9 | +这道题就是 [168](https://leetcode.wang/leetcode-168-Excel-Sheet-Column-Title.html) 题的逆过程,其实之前已经讲过怎么转换了,可以先过去看一下。 |
| 10 | + |
| 11 | +类比于我们最熟悉的十进制,对于 `2019` 可以看成下边的样子。 |
| 12 | + |
| 13 | +$$2\times10^3+0\times10^2+1\times10^1+9\times10^0=2019$$ |
| 14 | + |
| 15 | +这道题本质上其实就是一个稍微有些不一样的 `26` 进制,具体为什么在 [168](https://leetcode.wang/leetcode-168-Excel-Sheet-Column-Title.html) 题中已经分析过了。 |
| 16 | + |
| 17 | +转换的话,其实只需要把上边基数 `10` 换成 `26` 即可。 |
| 18 | + |
| 19 | +$$...x_4\times26^3+x_3\times26^2+x_2\times26^1+x_1\times26^0$$ |
| 20 | + |
| 21 | +所以给定一个数的时候,我们可以从右往左算,依次乘 `26` 的 `0,1,2...` 次幂,再累加即可。 |
| 22 | + |
| 23 | +```java |
| 24 | +public int titleToNumber(String s) { |
| 25 | + char[] c = s.toCharArray(); |
| 26 | + int res = 0; |
| 27 | + int mul = 1; |
| 28 | + for (int i = c.length - 1; i >= 0; i--) { |
| 29 | + res = res + mul * (c[i] - 'A' + 1); |
| 30 | + mul *= 26; |
| 31 | + } |
| 32 | + return res; |
| 33 | +} |
| 34 | +``` |
| 35 | + |
| 36 | +`c[i] - 'A' + 1` 这里字符做差,就相当于 ASCII 码对应的数字做差,从而算出当前字母对应的数字。 |
| 37 | + |
| 38 | +# 解法二 |
| 39 | + |
| 40 | +上边是比较直接的解法,在 [这里](https://leetcode.com/problems/excel-sheet-column-number/discuss/52091/Here-is-my-java-solution) 又看到另外一种解法。 |
| 41 | + |
| 42 | +上边的解法我们是倒着遍历的,那么我们能不能正着遍历呢?换言之,如果先给你高位的数,再给你低位的数,你怎么进行累加呢。 |
| 43 | + |
| 44 | +其实在十进制运算中我们经常使用的,比如要还原的数字是 `2019`,依次给你数字 `2,0,1,9`。就可以用下边的算法。 |
| 45 | + |
| 46 | +```java |
| 47 | +int res = 0; |
| 48 | +res = res * 10 + 2; //2 |
| 49 | +res = res * 10 + 0; //20 |
| 50 | +res = res * 10 + 1; //201 |
| 51 | +res = res * 10 + 9; //2019 |
| 52 | +``` |
| 53 | + |
| 54 | +直观上,我们每次乘 `10` 就相当于把每一位左移了一位,然后再把当前位加到低位。 |
| 55 | + |
| 56 | +那么具体上是为什么呢?还是要回到我们的等式 |
| 57 | + |
| 58 | +$$2\times10^3+0\times10^2+1\times10^1+9\times10^0=2019$$ |
| 59 | + |
| 60 | +将所有的 `10` 提取出来 。 |
| 61 | + |
| 62 | +$$10\times(2\times10^2+0\times10^1+1\times10^0)+9=2019$$ |
| 63 | + |
| 64 | +$$10\times(10\times(2\times10^1+0\times10^0)+1)+9=2019$$ |
| 65 | + |
| 66 | +$$10\times(10\times(10\times(10\times0 + 2)+0)+1)+9=2019$$ |
| 67 | + |
| 68 | +然后我们就会发现,我们每次做的就是将结果乘以 `10`,然后加上给定的数字。 |
| 69 | + |
| 70 | +而对于 `26` 进制是一样的道理,只需要把 `10` 改成 `26` 即可。 |
| 71 | + |
| 72 | +```java |
| 73 | +public int titleToNumber(String s) { |
| 74 | + char[] c = s.toCharArray(); |
| 75 | + int res = 0; |
| 76 | + for (int i = 0; i < c.length; i++) { |
| 77 | + res = res * 26 + (c[i] - 'A' + 1); |
| 78 | + } |
| 79 | + return res; |
| 80 | +} |
| 81 | +``` |
| 82 | + |
| 83 | +# 总 |
| 84 | + |
| 85 | +这道题依旧是进制转换。 |
0 commit comments