为了账号安全,请及时绑定邮箱和手机立即绑定

随机取一个整数,进行拆分,拆分后相加合大于9的话继续拆,直到小于9。

随机取一个整数,进行拆分,拆分后相加合大于9的话继续拆,直到小于9。

largeQ 2019-03-21 18:15:47
java实现 新手,用字符串拆分怎么实现?比如100拆成1,0,0 相加大于9的话就继续拆,小于9就输出
查看完整描述

3 回答

?
慕工程0101907

TA贡献1887条经验 获得超5个赞

这个用直接的方法,感觉没啥难的。


/**

 * Created by weixuan on 16/6/5.

 */

public class Test {


    // 第一步 to char


    public static char[] toChar(Integer data) {

        String value = String.valueOf( data );

        return value.toCharArray();

    }


    // 相加

    public static Integer add(char[] data) {

        Integer sum = 0;

        for (char d : data) {

            sum += d - '0';

        }

        return sum;

    }


    // 判断是否大于9

    public static Integer isBiggerCore(Integer data) {

        return add( toChar( data ) );

    }


    public static Integer isBigger(Integer data) {

        int value = data;

        int temp = isBiggerCore( data );

        while (temp > 9) {

            value = temp;

            temp = isBiggerCore( value );

        }

        return value;

    }


    // 987 -> 24

    // 99 -> 18

    // 199 -> 10

    public static void main(String[] args) {


        System.out.println(isBigger( 987 ));

    }

}


查看完整回答
反对 回复 2019-04-19
  • 3 回答
  • 0 关注
  • 403 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号