Java 笨方法获取一个四位数,每一位的值

本文详细讲解了如何通过位运算从4321这个四位数中分别提取千位、百位、十位和个位,并计算它们的和。通过实例展示了如何利用整数除法和取余操作实现位级处理。
部署运行你感兴趣的模型镜像
package lx;

public class lx {
    public static void main(String[] args) {
        /**
         * 假设一个数字4321 如何分别取出 千位 百位 十位 个位
         * 各个位的和
         *
         *
         * 个位bai(数) = units (digit)
         * 十位du(数) = tens (digit)
         * 百位(数) = hundreds (digit)
         * 千位zhi(数) = thousands (digit)
         * 万位dao(数) = ten thousands (digit)
         * 十万位(数) = hundred thousands (digit)
         */

        int num = 4321;
        int thousands = 0 ;
        int hundreds = 0 ;
        int tens = 0;
        int units = 0;

		int sum = 0;

        thousands = num /1000;
        System.out.println("千位的值是: "+thousands);

        num = num - thousands * 1000;
        hundreds =  num / 100;
        System.out.println("百位的值是: "+hundreds);

        num = num - hundreds * 100;
        tens = num / 10;
        System.out.println("十位的值是: "+tens);

        num = num - tens * 10;
        units = num;
        System.out.println("个位的值是: "+units);


		sum = thousands +hundreds+tens+units;
		 System.out.println("各各位的和: "+sum);
}
7.取一个4位数,各各位的数字
int num = 1234;
// 获取数字的千位
int thousands = num / 1000 ;
// 获取数字的百位
int hundreds = num / 100 % 10;
// 获取数字的十位
int tens = num / 10 % 10;
// 获取数字的个位
int one = num & 10;
// 求和
int sum = thousands + hundreds + tens + one;
System.out.print("和是:"+sum);```

您可能感兴趣的与本文相关的镜像

Python3.10

Python3.10

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值