leetcode 504. Base 7

来源:互联网 发布:社交网络 完整版 编辑:程序博客网 时间:2024/06/05 06:18

Given an integer, return its base 7 string representation.

Example 1:

Input: 100Output: "202"

Example 2:

Input: -7Output: "-10"

Note: The input will be in range of [-1e7, 1e7].

意思就是把十进制数转成七进制数。知道了转化规则那么一切就都好说了:

就是除以7取馀数.
例如
2753 = 393*7 +2
393 = 56*7 +1
56 = 8*7 + 0
8 = 1*7 +1
1 = 0*7 +1
(2753)|10 = ( 11012) |7

package leetcode;public class Base_7_504 {public String convertToBase7(int num) {if(num==0){return "0";}String result="";int numPositive=Math.abs(num);while(numPositive>=1){int yu=numPositive%7;result=yu+result;numPositive=numPositive/7;}if(num<0){result="-"+result;}return result;}public static void main(String[] args) {// TODO Auto-generated method stubBase_7_504 b=new Base_7_504();System.out.println(b.convertToBase7(0));}}
大神用了递归,也很不错。

public String convertTo7(int num) {    if (num < 0)        return '-' + convertTo7(-num);    if (num < 7)        return num + "";    return convertTo7(num / 7) + num % 7;}
还有大神善于使用java的函数,用one line解决:
return Integer.toString(Integer.parseInt(num+"", 10), 7); 

The formula for converting from one base to another is:

     return Integer.toString(Integer.parseInt(number, base1), base2);

原创粉丝点击