problem:
Related to question Excel Sheet Column Title
Given a column title as appear in an Excel sheet, and return its corresponding column number.
For example:
1, B, 2 C-3 ... 27 AA, Z
Analysis:
This problem are very easy. If you truely understand the principle of binary or decimal system. To represent a number a in the base of B. We havea0 A1 A2 ..... Covert it into the decimal system, we have (b^0) *a0 + (b^1) *a1 + (b^2) *A2 + .... Inch ThisProblem, Base is + (' A ' to ' Z '). for the digit at indexI, it is weight are:intDigit_weight = (int) Math.pow (+, S.length ()-1-i); one thing should is very careful, in Thismapping.' A ' is mapping-' 1 ' rather than ' 0 ', which means it starts from ' 1 ' to ' 26 '. The decimal number is just a-to represent it!Just as the mapping we have a done before (Hash). The important thing is to be able to recover it from the decimal number. Note:in Java, we don' t has power method fo integer, we have the use of force coverion here. (int) Math.pow (+, S.length ()-1-i);Static DoublePowDoubleADoubleb) Returns the value of the first argument raised to the power of the second argument.
Solution:
Public classSolution { Public intTitletonumber (String s) {if(s = =NULL) Throw NewIllegalArgumentException ("The passed in argument is invalid."); intres = 0; for(inti = 0; I < s.length (); i++) { intDigit_weight = (int) Math.pow (+, S.length ()-1-i); Res+ = (S.charat (i)-' A ' + 1) *Digit_weight; } returnRes; }}
[leetcode#171] Excel Sheet Column Number