[leetcode#171] Excel Sheet Column Number

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.