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++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
}; |
Java(可以利用內建函式)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public String convertToBase7(int num) { | |
return Integer.toString(num, 7); | |
} | |
} |
沒有留言:
張貼留言