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?  Yes

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+"";
        }
        Stackstack=new Stack();
        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;
    }
}

 

转载于:https://www.cnblogs.com/phdeblog/p/9069880.html

你可能感兴趣的:(763. Hex Conversion [LintCode naive])