JAVA小实例(十六)

本节的实例是一个实现一个数的数字特征值。

我写了俩种代码供大家参考:

第一个如下:

package test02;

import java.util.Scanner;

public class ShuZi01 
{
	public static void main(String[] args) 
	{
        Scanner in = new Scanner(System.in);
        System.out.println("请输入:");
        int number = in.nextInt();
        int g = number%10;
        int s = number/10%10;
        int b = number/100%10;
        int q = number/1000%10;
        int w = number/10000%10;
        int sw = number/100000%10;
        int bw = number/1000000%10;
        int newpr;
        int a,c,d,e,f,h,k;
        if(number!=0&&number<1000000)
      {
        if(g%2==1){
            a=1;
        }else{
            a=0;
        }

        if(s%2==0){
            c=1;
        }else{
            c=0;
        }

        if (b%2==1){
            d=1;
        }else{
            d=0;
        }

        if (q%2==0){
           e=1;
        }else{
            e=0;
        }

        if (w%2==1){
            f=1;
        }else{
            f=0;
        }

        if (sw%2==0){
            h=1;
        }else{
            h=0;
        }

        if (bw%2==1){
            k=1;
        }else{
            k=0;
        }
        
        newpr=a*(1)+c*(2)+d*(4)+e*(8)+f*(16)+h*(32)+k*(64);
        System.out.println("该数字对应的数字特征值为"+newpr);
      }else
      {
    	  System.out.println("System Error! Please input your number again!");
      }
    }
}

这一个比较易于理解,但比较繁琐。我们再来看一下第二种代码:

package test02;

import java.util.Scanner;

public class ShuZi02 
{
	public static void main(String[] args) 
	{
        // TODO Auto-generated method stub
        Scanner in = new Scanner(System.in);
        System.out.println("请输入:");
        int number=in.nextInt(),count=0,binary=0,a;
        do
        {
            a = number%10;
            if( (a%2 == 0 && (count+1)%2 == 0) || (a%2 != 0 && (count+1)%2 != 0))
            {
                binary=binary+(int)(Math.pow(2, count));
            }
            number = number/10;
            count+=1;
        }while(number != 0);
        System.out.println("该数字对应的数字特征值为"+binary);
        in.close();
    }
}

第二种比较简洁。大家有什么想法可以评论区交流交流。

我们下期再见!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

一字赌团队阿志

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

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

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

打赏作者

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

抵扣说明:

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

余额充值