763. Hex Conversion [LintCode naive]

Description

Given a decimal number n and an integer k, Convert decimal number n to base-k.

1.0<=n<=2^31-12<=k<=16
2.Each letter over 9 is indicated in uppercase

Have you met this question in a real interview?  

Example

Example 1:
Given n = 5k = 2
return "101"

Example 2:
Given n = 30k = 16
return "1E"

题目分析:典型的进制的转化问题,总结一下,有两种思路,一种不用栈,一种用栈。
思路一:
 public String hexConversion(int n, int k) {
        if(n==0){
            return 0+"";
        }
        int temp=0;
        String s="";
        while(n!=0){
            temp=n%k;
            if(temp>9){
              s=(char)(temp-10+'A')+s;
            }else{
                s=temp+s;
            }
            n=n/k;
        }
        return s;
    }
}

思路二:

public class Solution {
    /**
     * @param n: a decimal number
     * @param k: a Integer represent base-k
     * @return: a base-k number
     */
    public String hexConversion(int n, int k) {
        //write your code here
        if(n==0){
            return 0+"";
        }
        Stack<Integer>stack=new Stack<Integer>();
        int temp=0;
        while(n!=0){
            temp=n%k;
            n=n/k;
            stack.push(temp);
        }
        String s="";
        char c;
        while(!stack.isEmpty()){
            temp=stack.pop();
            if(temp>9){
              c=(char)(temp-10+'A');
              s=s+c;
            }else{
                s=s+temp;
            }
        }
        return s;
    }
}

猜你喜欢

转载自www.cnblogs.com/phdeblog/p/9069880.html
hex