763 Hex Conversion

原题网址:http://www.lintcode.com/zh-cn/problem/hex-conversion/

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

样例

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

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

标签 
 
 1 class Solution {
 2 public:
 3     /**
 4      * @param n: a decimal number
 5      * @param k: a Integer represent base-k
 6      * @return: a base-k number
 7      */
 8     string hexConversion(int n, int k) {
 9         // write your code here
10         if (n==0)
11     {
12         return "0";
13     }
14     
15     char ch[16]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};//定义为int数组也可以;
16     string result="";
17     int mod=0;
18     while(n!=0)
19     {
20         mod=n%k;
21         n=n/k;
22         result.push_back(ch[mod]);
23     }
24     reverse(result.begin(),result.end());
25     return result;
26     }
27 };

 

posted @ 2018-03-29 21:53  eeeeeeee鹅  阅读(280)  评论(0编辑  收藏  举报