504. Base 7
题目:
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].
链接:https://leetcode.com/problems/base-7/#/description
3/30/2017
17ms
1. 要注意负数
2. 第11行int到char转化
3. 题中负数到正数不会溢出,但是如果去掉范围条件呢?
1 public class Solution { 2 public String convertToBase7(int num) { 3 StringBuilder sb = new StringBuilder(); 4 StringBuilder r = new StringBuilder(); 5 if (num == 0) return "0"; 6 if (num < 0) { 7 r.append('-'); 8 num = -num; 9 } 10 while (num != 0) { 11 sb.append((char)(num % 7 + '0')); 12 num /= 7; 13 } 14 15 return r.append(sb.reverse()).toString(); 16 } 17 }
更多讨论: