首页 > 其他 > 详细

Base 7

时间:2017-02-13 22:01:32      阅读:233      评论:0      收藏:0      [点我收藏+]

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].

 

 1 public class Solution {
 2     public String convertToBase7(int num) {
 3         if (num == 0) return "0";
 4         
 5         StringBuffer result = new StringBuffer();
 6         Boolean isNegative = false;
 7         if (num < 0) {
 8             isNegative = true;
 9             num = -num;
10         }
11         
12         while (num != 0) {
13             int insertMe = num % 7;
14             result.insert(0, Integer.toString(insertMe));
15             num /= 7;
16         }
17         if (isNegative) result.insert(0, "-");
18         return result.toString();
19     }
20 }

 

 1 public class Solution {
 2     public String convertToBase7(int num) {
 3         if (num == 0) return "0";
 4         
 5         Boolean isNegative = num < 0;
 6         num = Math.abs(num);
 7         
 8         String result = "";
 9         while (num != 0) {
10             result = Integer.toString(num % 7) + result;
11             num /= 7;
12         }
13         return isNegative ? "-" + result : result;
14     }
15 }

 

Base 7

原文:http://www.cnblogs.com/amazingzoe/p/6395274.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!