Determine the number of digits, get each digit, and the integer reverse order (java)

topic:

Give a positive integer no more than 5 digits:

  1. Determine how many digits he is
  2. Output each digit separately
  3. Output the digits in reverse order. Such as 123-》321

Code:

public class Reverse{
    
    
	public static void main(String[] args) {
    
    
	
		Scanner scanner = new Scanner(System.in);
		int num = scanner.nextInt(); 
		
功能1:1234/10=123 -> 123/10=12 -> 12/10=1 -> 1/10=0; -> 0/10=0 判断位数
//		int count=0;
//		while(num!=0) {
    
    
//			num/=10;
//			count++;
//		}
		
功能2:1234%10=4   -> 123%10=3  -> 12%10=2 ->1%10=1   -> 0%10=0 判断每位数字
//		while(num!=0){
    
    
//			int bit=num%10;
//			System.out.println(bit);
//			num/=10;
//		}
		
//功能3:321=3*100+2*10+1*1    ,需要整合上面两个功能
		int count=0;//统计位数
		int src=num;//保存原数
		int result=0;
		
		while(num!=0) {
    
    //num为0才结束
			num/=10;
			count++;
		}
		
		num=src;//恢复原值
		while (num != 0) {
    
    
		    //判断每位数字 并乘 逆序后的权重
			int temp = (int) ((num % 10) * Math.pow(10, count - 1));//注意括号
			result += temp;
			num /= 10;
			count--;
		}
		System.out.println(result);
	}
}

Guess you like

Origin blog.csdn.net/qq_41571459/article/details/113092133