三十六進制加法
阿新 • • 發佈:2018-02-14
class add clas char static res solution while private
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")); } }
三十六進制加法