繁体   English   中英

怎么计算! 构造一个算法,允许您输入一个 4 位 integer 并计算第一位和最后一位数字的总和

[英]How to calculate! Construct an algorithm that allows you to enter a 4-digit integer and calculate the sum of the first and last digits

public static void main(String[] args) {
    
    Scanner sc = new Scanner (System.in);
    System.out.println("Ingresa el número: ");
    Integer numero = sc.nextInt();
    char[] nums = numero.toString().toCharArray();
}

我想这就是你要找的。 该算法将首先检查数字中的位数,如果它们是 4 则允许进一步处理,否则它将说 integer 是允许的 4 位数。

Scanner sc = new Scanner (System.in);
        System.out.println("Ingresa el número: ");
        Integer numero = sc.nextInt();
        if(Math.floor(Math.log10(numero)) + 1 != 4 ) {
            System.out.println("Integer should be of four digits");
        } else {
            int last = numero%10;
            int first = numero/1000;
            System.out.println(last+first);
        }

我认为这就是你想要的:

int answer = n%10 + n/1000;

它将数字 n 的第一位和最后一位数字相加。

你可以做这样的事情

Scanner sc = new Scanner (System.in);
System.out.println("Ingresa el número: ");
String numero = sc.nextLine();

Integer result = Integer.parseInt(numero.charAt(0)+"") +
    Integer.parseInt(number.charAt(numero.length()-1)+"");

你的意思是这样吗?

public class Adder {

    public static void main(String[] args) {
        int num=2008;
        
        //Find last number
        int sum = num%10;
        //Find first number
        while (num >= 10){
            num /= 10;
        }
        sum +=num;

        System.out.println(sum);
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM