public class Demo07 {
public static void main(String[] args) {
int n = 234;
System.out.println(subtractProductAndSum(n));
}
public static int subtractProductAndSum(int n) {
if (n<10){
return 0;
}
int product = 1;
int sum = 0;
int length = (int) ((Math.log(n)) / (Math.log(10)) + 1); // 判断整数类型数据长度的方法
// 最大位上的数用"除法"拿出来,个位用”取余“,中间位置,先”取余“后”除法“
for (int i = 1; i <= length; i++) {
if (i == 1) {
int a = (int) (n % Math.pow(10, i));
product *= a;
sum += a;
}
if (1 < i && i < length) {
int a = (int) ((n % Math.pow(10, i)) / (Math.pow(10, i - 1)));
product *= a;
sum += a;
}
if (i == length) {
int a = (int) (n / Math.pow(10, i - 1));
product *= a;
sum += a;
}
}
return product - sum;
}
}
计算返整数各位数字之积与各位数字之和的差
于 2023-04-03 21:44:46 首次发布