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].
這道題給了我們一個數,讓我們轉為七進制的數,而且這個可正可負。那么我們想如果給一個十進制的100,怎么轉為七進制。我會先用100除以49,商2余2。在除以7,商0余2,於是就得到七進制的202。其實我們還可以反過來算,先用100除以7,商14余2,然后用14除以7,商2余0,再用2除以7,商0余2,這樣也可以得到202。這種方法更適合於代碼實現,要注意的是,我們要處理好負數的情況,參見代碼如下:
解法一:
class Solution { public: string convertToBase7(int num) { if (num == 0) return "0"; string res = ""; bool positive = num > 0; while (num != 0) { res = to_string(abs(num % 7)) + res; num /= 7; } return positive ? res : "-" + res; } };
上面的思路也可以寫成迭代方式,非常的簡潔,僅要三行就搞定了,參見代碼如下:
解法二:
class Solution { public: string convertToBase7(int num) { if (num < 0) return "-" + convertToBase7(-num); if (num < 7) return to_string(num); return convertToBase7(num / 7) + to_string(num % 7); } };
參考資料:
https://discuss.leetcode.com/topic/78934/1-line
https://discuss.leetcode.com/topic/78972/simple-java-oneliner-ruby
https://discuss.leetcode.com/topic/78935/java-1-liner-standard-solution
