763. Hex Conversion [LintCode naive]

Description

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

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

Have you met this question in a real interview?  Yes

Example

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

Example 2:
Given n = 30k = 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; } }
相關文章
相關標籤/搜索