0

Java把int型数字转换为string型

Posted by 撒得一地 on 2016年4月19日 in 杂谈
public class IntToString {

    /**
     * Algorithm implementation based on the module of a given number and

     * iterate until the number is zero. With this approach we get a complexity

     * order equals to O(N) in time terms where N is the number of digits in the

     * given integer. In space terms, the complexity order is also O(N) because

     * we are using an StringBuilder as auxiliary data structure.

     */

    public String transform(int number) {

        boolean isNegative = false;

        StringBuilder sb = new StringBuilder();

        if (number == 0) {

            return "0";

        } else if (number < 0) {

            isNegative = true;

        }

        number = Math.abs(number);

        while (number > 0) {

            sb.append(number % 10);

            number /= 10;

        }

        if (isNegative) {

            sb.append("−");

        }

        return sb.reverse().toString();

    }

}

上一篇:

下一篇:

相关推荐

发表评论

电子邮件地址不会被公开。 必填项已用*标注

6 + 5 = ?

网站地图|XML地图

Copyright © 2015-2024 技术拉近你我! All rights reserved.
闽ICP备15015576号-1 版权所有©psz.