面试-阿里社招笔试题两则(一)----Excel列号转数字

Excel列号转数字

根据excel列号计算列数以及根据列号计算列数,excel中的列数是使用字母表示的,即A,B,C…Z,AA…,ZZ…这种情况,假设我们输入A,那么输出结果为1,输入27,输出结果为AA,以此类推。

解答:考虑和十进制转二十六进制联系起来,本质上是一样的问题。

package com.lhc.translate;

import org.junit.Test;

/**
 * @description:
 * @author: hjt
 * @create: 2020-07-19 15:55
 */
public class ExcelNumber {

    /**
     * 根据excel列号计算列数以及根据列号计算列数,excel中的列数是使用字母表示的,即		A,B,C...Z,AA...,ZZ....这种情况,
     * 假设我们输入1,那么输出结果为1,输入27,输出结果为AA,以此类推。
     *
     * @param num
     * @return
     */
    public static String numCovertLetter(int num) {
        String str = "";
        while (num > 0) {
            int res = num % 26;
            if (res == 0) {
                res = 26;
            }
            str = (char) (res + 64) + str;
            num = (num - res) / 26;
        }
        return str;
    }

    @Test
    public void testNumCovertLetter() {
        int num = 703;
        System.out.println(numCovertLetter(num));
    }


  • 补充-1 : 由列号来转换数字(把上面的思路反过来)
    /**
     * 反过来根据列号来计算数字
     *
     * @param str
     * @return
     */
    public static int letterCovertNum(String str) {
        int sum = 0;
        char[] arr = str.toCharArray();
        int n = str.length();
        for (int i = 0; i < n; i++) {
            /**
             * arr[i] - 64:A=65-64=1、B=66-64=2
             * n位数=n位数字*26的n-1次方
             */
            sum += (arr[i] - 64) * Math.pow(26, n - (i + 1));
        }
        return sum;
    }

    @Test
    public void testLetterCovertNum() {
        String str = "AAA";
        System.out.println(letterCovertNum(str));
    }

补充-2 : 10进制转换n进制

这个代码和原来代码稍微有点区别

	/**
     * 10进制 转换 n 进制
     *
     * @param num
     * @param n
     * @return
     */
    public static String numCovertN(int num, int n) {
        if (num <= 0) {
            throw new RuntimeException("参数必须大于0");
        }
        String str = "";
        while (num > 0) {
            int res = num % n;
            /*if (res == 0) {
                res = pos;
            }*/
            str = res + str;
            num = (num - res) / n;
        }
        return str;
    }

    @Test
    public void testNumCovertN() {
        System.out.println(numCovertN(5, 3));
    }

补充-3:n进制转换10进制


    /**
     * n 进制转换 10进制
     *
     * @param str
     * @return
     */
    public static int NCovertNum(String str, int n) {
        int sum = 0;
        char[] arr = str.toCharArray();
        int length = str.length();
        for (int i = 0; i < length; i++) {
            sum += (arr[i] - 48) * Math.pow(n, length - (i + 1));
        }
        return sum;
    }

    @Test
    public void testNConvertNum(){
        System.out.println(NCovertNum("12", 3));
    }
}

猜你喜欢

转载自blog.csdn.net/TP89757/article/details/107448950
今日推荐