使用算术运算符得到一个 4 位十进制数的各位数字并输出,然后输出该数 的逆序数和各位数字平方后相加的和利用java
时间: 2024-10-15 08:26:27 浏览: 35
在Java中,你可以通过位运算来获取一个4位十进制数的每一位,并结合数学操作计算出逆序数以及每位数字平方之和。这里是一个示例:
```java
public class Main {
public static void main(String[] args) {
int num = 1234; // 这是我们想要处理的4位数
int reversedNum = reverse(num); // 取逆序数
int sumOfSquares = getSumOfDigitsAndReverse(num); // 求平方和
System.out.println("原始数: " + num);
System.out.println("逆序数: " + reversedNum);
System.out.println("各位数字平方和: " + sumOfSquares);
}
// 位运算提取每位数字
private static int getDigit(int n, int pos) {
return (n >> pos) & 0x0f;
}
// 获取逆序数
private static int reverse(int num) {
int reversed = 0;
for (int i = 0; i < 4; i++) {
reversed <<= 4;
reversed |= getDigit(num, i);
}
return reversed;
}
// 计算各位数字的平方和,并包括逆序数
private static int getSumOfDigitsAndReverse(int num) {
int sum = 0;
for (int digit : new int[]{getDigit(num, 0), getDigit(num, 1), getDigit(num, 2), getDigit(num, 3)}) {
sum += digit * digit;
}
return sum + reverse(num);
}
}
```
在这个程序中,`getDigit()`函数通过位移和按位与操作获取每个位置的数字,`reverse()`函数通过位左移和按位或操作将数字反转,最后`getSumOfDigitsAndReverse()`函数计算各位数字的平方总和加上逆序数。
阅读全文
相关推荐


















