每日一练 LeetCode:E504. 七进制数

题目

给定一个整数 num,将其转化为 7 进制,并以字符串形式输出。

示例 1:

输入: num = 100
输出: "202"
示例 2:

输入: num = -7
输出: "-10"

代码

/**
 * 504. 七进制数  https://leetcode-cn.com/problems/base-7/
 *
 * 给定一个整数 num,将其转化为 7 进制,并以字符串形式输出。
 */
public class E504 {

    // 1-2 ms.
//    public static String convertToBase7(int num) {
//
//        if (num == 0) {
//            return "0";
//        }
//
//        String res = "";
//        int quotient = Math.abs(num);
//
//        while (quotient != 0) {
//            res = res.concat(Integer.toString(quotient % 7));
//            quotient /= 7;
//        }
//
//        return (num < 0 ? "-" : "") + new StringBuilder(res).reverse().toString();
//    }

    public static String convertToBase7(int num) {
        return Integer.toString(num,7);
    }

    public static void main(String[] args) {
        System.out.println(convertToBase7(100));
    }

}
Integer.toString(int i, int radix)

看一下它的源码,效率确实块。

    public static String toString(int i, int radix) {
        if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
            radix = 10;

        /* Use the faster version */
        if (radix == 10) {
            return toString(i);
        }

        char buf[] = new char[33];
        boolean negative = (i < 0);
        int charPos = 32;

        if (!negative) {
            i = -i;
        }

        while (i <= -radix) {
            buf[charPos--] = digits[-(i % radix)];
            i = i / radix;
        }
        buf[charPos] = digits[-i];

        if (negative) {
            buf[--charPos] = '-';
        }

        return new String(buf, charPos, (33 - charPos));
    }
    
    /**
     * All possible chars for representing a number as a String
     */
    final static char[] digits = {
        '0' , '1' , '2' , '3' , '4' , '5' ,
        '6' , '7' , '8' , '9' , 'a' , 'b' ,
        'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,
        'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,
        'o' , 'p' , 'q' , 'r' , 's' , 't' ,
        'u' , 'v' , 'w' , 'x' , 'y' , 'z'
    };

附:测试图

在这里插入图片描述

来源

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/base-7

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值