leetcode brush notes --Excel title list name

Subject description:

Given a positive integer, it returns an Excel table corresponding to the column name

Such as:

1:A

2:B

28: AB

701: ZY

Problem-solving ideas:

This question is marked on leetcode is simple, so I thought it was bronze, finished I did not expect was a king. Studied a morning head is knotted, or thought to understand. Read other people's explanations noon Sleep still wondering, finally understand 7788. I put the code to move over, talk about their own understanding (Which brother moved infringement of saying loudly Kazakhstan)

AC Code:

public String convertToTitle1(int n){
        String temp = "";
        while (n > 0){
            char s = (char)((n-1) % 26 + 'A');
            temp = s + temp;
            n = (n-1)/26;
        }
        return temp;
    }

Initially I thought it was a simple binary decimal conversion of 26 questions, and then after touched the wall several times found things are not so simple.

Note that the code denoted by the two n-1.

Look at the first n-1, 1 to 26 decimal digits corresponding to the letters A ~ Z, so that when the A base point number n = 1 ~ 26 A ~ Z were changed when adding it in the 0-25 should therefore again reduce a modulo basis of the decimal number. But it can not be written char s = (char) (n% 26 + 'A'-1), such as write, when n is divisible by 26, would be "the Z', and this would be calculated ' A'-1 = '@'.

As for the second n-1, I do not know you have not noticed the difference excel sequence and decimal. Decimal bits take full ten less than 1, that is to say to take full bit 9, ten 1 is represented by 10. And this sequence can excel appear AZ, A represents a 26, Z also represents a 26, which is very lost right, here it is full and then into the 27-bit, but it represents 26 into bits. Therefore, in order to prevent a multiple of 26, for example, 52 becomes BZ, because most have been consumed at the end of a 26, only a 26 to enter one before. Thus a second n-1 is to prevent this from happening.

Actually, I think in the final analysis, this question fans reason is that it does not meet our thinking inertia. We decimal, binary, hexadecimal, and so each is 0, and this sequence does not exist excel 0, only 1-26, and it is full of 27 (instead of its hex 26) only one forward.

 

Guess you like

Origin www.cnblogs.com/yingying7/p/11578855.html