One small practice every day (the difference between "the product of your numbers" and "the sum of your numbers")

Description of the topic: Enter an integer n, please calculate and return the difference between the "product of digits" and "sum of digits" of the integer

  • E.g:
  • Input: 234
  • Returns: 15
  • Explanation: The product of the digits = 2 * 3 * 4 = 24
  • The sum of the digits = 2 + 3 + 4 = 9
  • Result = 24-9 = 15

Ideas:
1. Input, create an input object of the Scanner class, and use the ( nextInt() ) method to save the input integer to an int type number. And define variables, the sum of digits (sum) and initialize to 0, the product of digits (result) and initialize to 1.
2. Get each digit in number
Method 1: Use the while loop to take the remainder of number to 10, get the last digit, accumulate and accumulate and store them in sum and result, take the quotient of 10 and assign it to number, When number is equal to 0, the loop ends.
Method 2: Convert the int type number to String type ( String.valueOf()) , use the for loop and the ( charAt() ) method in the String class to obtain each character one by one, but the obtained character cannot be valued Calculation, so we need to convert char to String ( String.valueOf() ), and then to int type ( Integer.parseInt() ) for accumulation and accumulation.
3. Find the difference and output

code show as below:

import java.util.Scanner;

public class Test01 {
    
    
	public static void main(String[] args) {
    
    
		
		Scanner input=new Scanner(System.in);
		System.out.println("请输入一个整数:");
		
		int number=input.nextInt();
		
		int sum=0,result=1;
		
		//方式1:
//		while(number!=0){
    
    
//		  int n=number%10;   //获取当前整数的个位数字
//		  System.out.println(n);
//		  sum+=n;    //累加
//		  result*=n;     //累积
//		  
//		  number/=10;
//		}

		//方式2:
		//将int类型的整数,转换成String类型的字符串
		String strNumber=String.valueOf(number);
		
		//逐个获取字符串中的每个字符
		for(int i=0;i<strNumber.length();i++){
    
    
			//获取当前字符
			char c=strNumber.charAt(i);
			
			// 字符 => 字符串 => 整型
			String s=String.valueOf(c);// 字符 => 字符串
			int n=Integer.parseInt(s);//字符串 => 整型
			
			sum+=n;//累加
			result*=n;//累积
		
		}
	
		System.out.println(result-sum);
	}
		
}

Guess you like

Origin blog.csdn.net/weixin_51529267/article/details/112718548