【问题标题】:How to find sum of first three digits如何求前三位数字的总和
【发布时间】:2016-06-13 20:35:15
【问题描述】:

我是 Java 新手,我尝试在 int 数字中找到前三位数字的总和。 我有一个数字123456 我想找到前三位数字的总和123,然后找到后三位数字的总和456,然后进行比较。我不明白该怎么做。我接下来编码:

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter the number:");
    int number = scanner.nextInt();
    int length = (int) Math.ceil(Math.log10(number));

    for (int i = 1; i <= 3; i++) {
        System.out.println(i);
    }

    System.out.println(length);
    System.out.println(number);
}

我认为我应该使用 for 循环,但我不确定。我知道如何计算数字的长度。但是如何求前三个数和后三个数之和呢?

【问题讨论】:

  • 如果您使用scanner.next() 将号码作为String 获取,您会发现会更容易。然后你可以简单地使用length()substring()
  • 如果号码少于 6 位怎么办?
  • @Tunaki 只适合初学者,我认为他们不需要担心清理输入 - 他们只是想看看代码的逻辑工作。

标签: java loops if-statement while-loop


【解决方案1】:

假设你的长度是恒定的 (6):

String first = (""+number).substring(0, 3);
String second = (""+number).substring(3, 6);
int firstSum = 0;
int secondSum = 0;
for (int x = 0; x < first.length; x++)
    firstSum += Integer.parseInt(first.charAt(x)+"");
for (int x = 0; x < second.length; x++)
    secondSum += Integer.parseInt(second.charAt(x)+"");
System.out.println("Sum of first 3: " + firstSum);
System.out.println("Sum of second 3: " + secondSum);

阅读String API- 它有很多有用的方法。对于像这样的小程序,通常很容易转换为 String,使用 String 方法,然后解析回 int。

编辑:Andy Turner 和 Jeremy Kato 告诉我Character.getNumericValue()。因此,声明:

firstSum += Integer.parseInt(first.charAt(x)+"");

可以改为:

firstSum += Character.getNumericValue(first.charAt(x));

secondSum 也是如此。

【讨论】:

  • 您可以在不使用Character.getNumericValue(char)创建字符串的情况下提取数字值。
【解决方案2】:

首先,可能应该更正您的长度拼写 - 尽管可能不是,因为您并不需要该变量来执行此操作。

您的代码应该做的是立即将输入转换为int。您首先要将输入字符串分成两部分,然后将这两个数字用循环求和。

这是我的想法:

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter the number:");
    String input = scanner.nextLine();

    String firstHalf = input.substring(0, 3); // note that depending on how 
                // many digits you want to change, these numbers must change as well.
    String secondHalf = input.substring(3); 

    int sum1 = 0;
    int sum2 = 0;


    // don't forget: start at 0, not 1!
    for(int i = 0; i<=3; i++){

        sum1 += Character.getNumericValue(firstHalf.charAt(i));     
        sum2 += Character.getNumericValue(secondHalf.charAt(i));
        // this call to the Character class converts a character to an int. 

    }

    System.out.println(sum1);
    System.out.println(sum2);

}

请注意,此代码适用于您输入的 6 个字符,并且假定它们将是数字。如果您输入的字符太少或输入字母,它会崩溃,但您可以稍后再担心。

【讨论】:

    【解决方案3】:

    这是一种简单的方法,假设您的整数具有偶数位数......

    public class Test {
        public static void main(String[] args) {
            // Makes the assumption that the input integer contains an even number of digits.
            int x = 123456;
            String s = Integer.toString(x);
            int[] count = new int[2];
            for (int i = 0; i < s.length(); i++) {
                int digit = Integer.parseInt(s.substring(i, i + 1));
                int countIndex = (int)Math.floor(i * 2 / s.length());
                count[countIndex] += digit;
            }
    
            int half = s.length() / 2;
            System.out.println("First Sum of " + s.substring(0, half) + ": " + count[0]);
            System.out.println("Second Sum of " + s.substring(half) + ": " + count[1]);
        }
    }
    

    替代方法

    这是另一种不使用上述数组的方法,实际上通过将总和抽象为一个方法来简化逻辑。

    public class Test {
        public static void main(String[] args) {
            // Makes the assumption that the input integer contains an even number of digits.
            int x = 123456;
            String s = Integer.toString(x);
            int half = s.length() / 2;
            String firstHalf = s.substring(0, half);
            String secondHalf = s.substring(half);
            System.out.println(firstHalf);
            System.out.println(secondHalf);
            int sum1 = sumString(firstHalf);
            int sum2 = sumString(secondHalf);
            System.out.println("Sum 1: " + sum1);
            System.out.println("Sum 2: " + sum2);
        }
    
        private static int sumString(String s) {
            int sum = 0;
            for (int i = 0; i < s.length(); i++) {
                sum += Integer.parseInt(s.substring(i, i + 1));
            }
    
            return sum;
        }
    }
    

    【讨论】:

    • 谢谢它的工作!据我了解,您使用数组。我还没有研究过数组。
    • 我用另一种方法更新了我的答案,没有任何数组(尽管这只是为了便于存储总和)并将总和抽象为一个新方法。
    【解决方案4】:

    这是一个不使用字符串或数组的替代解决方案:

    public static void main(String args[]){
        int num=123456;
        int second = 0;
        int first = 0;      
    
        second = addLastThree(num);
        num /= 1000;
        first = addLastThree(num);
    
        System.out.println("first -- > " + first);
        System.out.println("second -- > " + second);
    
    
    }
    
    static int addLastThree(int num){
        int sum = 0;
        for (int i =0; i<3; i++){
            sum += (num/Math.pow(10,i)) % 10;
        }   
        return sum;
    }   
    

    【讨论】:

      【解决方案5】:

      你可以试试这段代码,每一行都在 cmets 中解释了。

      public static void main(String[] args) {
          Scanner scanner = new Scanner(System.in);
          System.out.println("Enter the number:");
          int number = scanner.nextInt();
          int n=number; //duplicating the value for the reference.
      int l = (int) Math.log10(number) + 1; //Length of the number
      int half = l/2; //to find half length of the number to sum first and last digits seperately.
      int last_Sum = 0; //to store sum of last digits
      int first_Sum = 0; //to store sum of first digits
      for(int i=0; i<half && number>0; i++){ //to sum last digits
          last_Sum = last_Sum + number%10;
          number = number/10;
      }for(int i=0; i<half && number>0; i++){ //to sum first digits
          first_Sum = first_Sum + number%10;
          number = number/10;
      }
      System.out.println("Length of the number "+l);
      System.out.println("Number is "+n);
      System.out.println("Sum of last digits "+last_Sum);
      System.out.println("Sum of first digits "+first_Sum);}}
      

      【讨论】:

        猜你喜欢
        • 2017-07-05
        • 2022-11-04
        • 2013-06-23
        • 1970-01-01
        • 1970-01-01
        • 2016-07-26
        • 1970-01-01
        • 2021-01-27
        • 1970-01-01
        相关资源
        最近更新 更多