zoukankan      html  css  js  c++  java
  • 三十六进制加法

    public class Solution
    {  
        /**
         * num1 num2 为两个三十六进制的数,计算相加结果
         * @param num1
         * @param num2
         * @return
         */
        public String add(String num1, String num2)
        {
            StringBuilder result = new StringBuilder();
            int carry = 0;
            int len1 = num1.length() - 1;
            int len2 = num2.length() - 1;
            for(; len1>=0 && len2>=0; len1--, len2--)
            {
                carry = add(num1, num2, result, carry, len1, len2);
            }
            
            while(len1>=0)
            {
                carry = add(num1, num2, result, carry, len1, len2);
                len1--;
            }
            while(len2>=0)
            {
                carry = add(num1, num2, result, carry, len1, len2);
                len2--;
            }
            if(carry > 0)
                result.append(carry);
            System.out.println(result.toString());
            return result.reverse().toString();
        }
    
        private int add(String num1, String num2, StringBuilder result, int carry, int len1, int len2)
        {
            int n1 = 0, n2 = 0;
            if(len1 >= 0)
            {
                n1 = getNumByChar(num1.charAt(len1));
            }
            if(len2 >= 0)
            {
                n2 = getNumByChar(num2.charAt(len2));
            }
            int sum = n1 + n2 + carry;
            carry = sum / 36;
            result.append(getCharByNum(sum % 36));
            return carry;
        }
        
        public char getCharByNum(int n)
        {
            if(n<10)
            {
                return (char)((int)'0' + n);
            }
            else
            {
                return (char)((int)'a' + (n-10));
            }
        }
        
        public int getNumByChar(char c)
        {
            if(c>=0 && c<=9)
            {
                return c - '0';
            }
            else
            {
                return (c - 'a') + 10;
            }
        }
        
        public static void main(String[] args)
        {
            System.out.println(new Solution().add("ab", "z"));
        }
        
    }
  • 相关阅读:
    c# 查找进程
    第三方打包工具
    WebClient 上传和下载
    .net 读取文件
    winfrom 圆角panel
    窗体或控件的两种拖动方式
    winfrom 获取当前屏幕尺寸
    动态修改配置文件web服务地址
    将字符串编码成 GBK
    .net(C#) 读取配置文件
  • 原文地址:https://www.cnblogs.com/woniu4/p/8448011.html
Copyright © 2011-2022 走看看