题解 | #36进制加法#

36进制加法

http://www.nowcoder.com/practice/c5db069fd9d64e6e9cf5fd68860abcdd

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param A string字符串 
     * @param B string字符串 
     * @return string字符串
     */
    public String thirtysixAdd(String A, String B) {
        // write code here
        HashMap<Character, Integer> CharacterToNumber = new HashMap<>();
        HashMap<Integer, Character> NumberToCharacter = new HashMap<>();
        for (int i = 0; i < 10; i++) {
            CharacterToNumber.put((char) ('0' + i), i);
            NumberToCharacter.put(i, (char) ('0' + i));
        }
        for (int i = 0; i < 26; i++) {
            CharacterToNumber.put((char) ('a' + i), i + 10);
            NumberToCharacter.put(i + 10, (char) ('a' + i));
        }
        int lenA = A.length();
        int lenB = B.length();
        int maxLen = Math.max(lenA, lenB);
        int pointA = lenA - 1;
        int pointB = lenB - 1;
        StringBuffer sb = new StringBuffer("");
        char[] chrsA = A.toCharArray();
        char[] chrsB = B.toCharArray();
        int carryBit = 0;
        while (pointA > -1 && pointB > -1) {
            char chrA = chrsA[pointA];
            char chrB = chrsB[pointB];
            int chrAValue = CharacterToNumber.get(chrA);
            int chrBValue = CharacterToNumber.get(chrB);
            int currentValue = chrAValue + chrBValue + carryBit;
            sb.append(NumberToCharacter.get(currentValue % 36));
            carryBit = currentValue / 36;
            pointA--;
            pointB--;
        }
        while (pointA > -1) {
            char chrA = chrsA[pointA];
            int chrAValue = CharacterToNumber.get(chrA);
            int currentValue = chrAValue + carryBit;
            sb.append(NumberToCharacter.get(currentValue % 36));
            carryBit = currentValue / 36;
            pointA--;
        }
        while (pointB > -1) {
            char chrB = chrsB[pointB];
            int chrBValue = CharacterToNumber.get(chrB);
            int currentValue = chrBValue + carryBit;
            sb.append(NumberToCharacter.get(currentValue % 36));
            carryBit = currentValue / 36;
            pointB--;
        }
        if (carryBit == 1) {
            sb.append(1);
        }
        sb.reverse();
        return new String(sb);
    }
}
全部评论

相关推荐

totoroyyw:千年老妖😂
投递华为等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务