Given a decimal number n
and an integer k
, Convert decimal number n
to base-k
.markdown
1.0<=n<=2^31-1
, 2<=k<=16
2.Each letter over 9 is indicated in uppercase
app
Example 1:
Given n
= 5
, k
= 2
return "101"
this
Example 2:
Given n
= 30
, k
= 16
return "1E"
spa
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; } }
思路二:code
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; } }