简体   繁体   中英

Sum of numbers between int low and int high; Java

I am trying to create a code in Java and I know this is wrong but I need a little help:

Given two integers low and high representing a range, return the sum of the integers in that range. For example, if low is 12 and high is 18, the returned values should be the sum of 12, 13, 14, 15, 16, 17, and 18, which is 105. If low is greater than high, return 0.

The solution I have is (I know it's not right, don't murder me pls):

public int sumRange(int low, int high)
{
    int sum = 0;
    for (int val = int low; val < int high; val++)
        sum += val;
    return val;
}

You have several issues.

  1. Incorrect loop syntax. You don't need to redeclare the type of existing variables.
  2. You return val instead of sum . Since val is scoped to the loop, this is a compile error.
  3. Your loop ends one too early. It doesn't include the largest value. To include it use <= rather than < .

Fixed code

public class RangeTest1 {

    public static void main(String[] args){

        System.out.println(sumRange(12, 18)); // prints 105
        System.out.println(sumRange(18, 12)); // prints 0
        System.out.println(sumRange(18, 18)); // prints 18
    }

    public static int sumRange(int low, int high)
    {
        int sum = 0;

        for (int val = low; val <= high; val++){
            sum += val;
        }

        return sum;
    }
}

You get the 0 if low is greater than high for free, as the loop never runs any iterations if this is the case. The initial value of 0 remains and is returned.

Or you could use math , although you have to be careful of overflow if high is very large:

public static int sumRange(int low, int high)
{
  return high >= low ? (high*(high+1) - low*(low-1))/2 : 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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