2018年3月6日 星期二

[LeetCode] 504. Base 7

轉自LeetCode

Given an integer, return its base 7 string representation.
Example 1:
Input: 100
Output: "202"
Example 2:
Input: -7
Output: "-10"
Note: The input will be in range of [-1e7, 1e7].
<Solution>

這題不難,直覺解就可以了

code 如下

C++
class Solution {
public:
string convertToBase7(int num) {
string ans = "";
int x = abs(num);
do {
ans = to_string(x%7) + ans;
x /= 7;
}while(x);
return num < 0 ? "-" + ans : ans;
}
};
view raw base7.cpp hosted with ❤ by GitHub

Java(可以利用內建函式)
class Solution {
public String convertToBase7(int num) {
return Integer.toString(num, 7);
}
}
view raw base7.java hosted with ❤ by GitHub

沒有留言:

張貼留言