平方圈怪

平方圈怪

package _07第七届;

  • 题目描述
    如果把一个正整数的每一位都平方后再求和,得到一个新的正整数。
    对新产生的正整数再做同样的处理。
    如此一来,你会发现,不管开始取的是什么数字,
    最终如果不是落入1,就是落入同一个循环圈。
    请写出这个循环圈中最大的那个数字。
    请填写该最大数字。
    注意:你提交的应该是一个整数,不要填写任何多余的内容或说明性文字。
    结果:145
public class Test03平方圈怪 {
public static void main(String[] args) {
    int start=3;
    int cnt=0;
    int max=0;
    while(cnt<1000) {  //做一千次循环测试
//    	System.out.println(start);
        int  sum=check(start);
        start=sum;  //继续循环
        if(start>max) {
        	max=start;
        }
        cnt++;
    }
    System.out.println(max);
}
private static  int check(int start) {
	// TODO Auto-generated method stub
	String str=start+""; //转换为字符串
	int ans=0;    
	for(int i=0;i<str.length();i++) {  //对字符串进行截取 平方
		ans+=(str.charAt(i)-'0')*(str.charAt(i)-'0');   //字符转换为数字
	}
	return ans;     //返回平方后相加的和
}
}

方法二

public class Main {
	public static void main(String[] args) {
		System.out.println(f(1234));
		System.out.println(f(12345));
		System.out.println(f(123));
		System.out.println(f(23456));
		// 计算结果都为145
	}
 
	public static int f(int num) {
		int max = 0;// 通过num计算出的最大值
		while (true) {
			int temp = 0;// 保存num本次计算的值
			while (num != 0) {
				temp += (num % 10) * (num % 10);
				num = num / 10;
			}
			num = temp;
			if(max == temp ){
				break;
			}else{
				max = (max > temp) ? max : temp;
			}
		}
		return max;
	}
}

第二方法来自:

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

金石不渝

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值