How to speed up the efficiency of my code? - java

Essentially I'm trying to create a program that counts up the sum of the digits of the number, but every time a number that is over 1000 pops up, the digits don't add up correctly. I can't use % or division or multiplication in this program which makes it really hard imo. Requirements are that if the user inputs any integer, n, then I will have to be able to compute the sum of that number.
I've already tried doing x>=1000, x>=10000, and so forth a multitude of times but I realized that there must be some sort of way to do it faster without having to do it manually.
import java.util.Scanner;
public class Bonus {
public static void main(String[] args) {
int x;
int y=0;
int u=0;
Scanner s = new Scanner(System.in);
System.out.print("Enter the number:");
x = s.nextInt();
int sum = 0;
{
while(x >= 100) {
x = x - 100;
y = y + 1;
}
while(x>=10) {
x = x - 10;
u = u + 1;
}
sum = y + u + x;
System.out.println("The sum of the digits in your number is" + " " + sum);
}
}
}
So if I type in 1,000 it displays 10. And if I type in 100,000 it displays 100. Any help is appreciated

Convert the number to a string, then iterate through each character in the string, adding its integer value to your sum.
int sum = 0;
x = s.nextInt();
for(char c : Integer.toString(x).toCharArray()) {
sum += Character.getNumericValue(c);
}

Related

How to reverse the order of an int without turning it into a string

I have been tasked with the assignment of creating a method that will take the 3 digit int input by the user and output its reverse (123 - 321). I am not allowed to convert the int to a string or I will lose points, I also am not allowed to print anywhere other than main.
public class Lab01
{
public int sumTheDigits(int num)
{
int sum = 0;
while(num > 0)
{
sum = sum + num % 10;
num = num/10;
}
return sum;
}
public int reverseTheOrder(int reverse)
{
return reverse;
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Lab01 lab = new Lab01();
System.out.println("Enter a three digit number: ");
int theNum = input.nextInt();
int theSum = lab.sumTheDigits(theNum);
int theReverse = lab.reverseTheOrder(theSum);
System.out.println("The sum of the digits of " + theNum + " is " + theSum);
}
You need to use the following.
% the remainder operator
/ the division operator
* multiplication.
+ addition
Say you have a number 987
n = 987
r = n % 10 = 7 remainder when dividing by 10
n = n/10 = 98 integer division
Now repeat with n until n = 0, keeping track of r.
Once you understand this you can experiment (perhaps on paper first) to see how
to put them back in reverse order (using the last two operators). But remember that numbers ending in 0 like 980 will become 89 since leading 0's are dropped.
You can use below method to calculate reverse of a number.
public int reverseTheOrder(int reverse){
int result = 0;
while(reverse != 0){
int rem = reverse%10;
result = (result *10) + rem;
reverse /= 10;
}
return result;
}

Print largest number out of given digits - Java

First I would apologize if my question seems not clear.
I want output to be the largest possible number from user input. Example:
input: x = 0; y = 9; z = 5;
output: 950
I tried something like the below code.
import java.util.Scanner;
class LargestOfThreeNumbers{
public static void main(String args[]){
int x, y, z;
System.out.println("Enter three integers ");
Scanner in = new Scanner(System.in);
x = in.nextInt();
y = in.nextInt();
z = in.nextInt();
if ( x > y && x > z )
System.out.println("First number is largest.");
else if ( y > x && y > z )
System.out.println("Second number is largest.");
else if ( z > x && z > y )
System.out.println("Third number is largest.");
}
}
The code above will print something like: The seconde number is largest. That is correct the way I define the conditional statements. But how do I get 950 as final result? I know some logic is required here but my brain doesn't seem to produce it.
Your help is appreciated.
You could do something like this to print the numbers in order:
// make an array of type integer
int[] arrayOfInt = new int[]{x,y,z};
// use the default sort to sort the array
Arrays.sort(arrayOfInt);
// loop backwards since it sorts in ascending order
for (int i = 2; i > -1; i--) {
System.out.print(arrayOfInt[i]);
}
A solution using java 8 IntStream:
int x = 0, y = 9, z = 5;
IntStream.of(x,y,z).boxed().sorted( (i1,i2) -> Integer.compare(i2, i1)).forEach( i -> System.out.print(i));
You can find the maximum with successive calls to Math.max(int, int) and the minimum with calls to Math.min(int, int). The first number is the max. The last is min. And the remaining term can be determined with addition of the three terms and then subtraction of the min and max (x + y + z - max - min). Like,
int max = Math.max(Math.max(x, y), z), min = Math.min(Math.min(x, y), z);
System.out.printf("%d%d%d%n", max, x + y + z - max - min, min);
Something like this would work
ArrayList<Integer> myList = new ArrayList<Integer>();
Scanner val = new Scanner(System.in);
int x = 0;
for (int i = 0; i < 3; i++) {
System.out.println("Enter a value");
x = val.nextInt();
myList.add(x);
}
myList.sort(null);
String answer = "";
for (int i = myList.size() - 1; i >= 0; i--) {
answer += myList.get(i).toString();
}
System.out.println(answer);
}

Why sum of odd numbers from 1 to the number entered doesn't match what was expected?

import java.util.Scanner;
public class OddSum {
public static void main(String[] args) {
int num;
int i = 1;
int sum = 0;
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
num = input.nextInt();
input.close();
while (i<=num) {
i += 2;
sum +=i;
}
System.out.println("The sum of odd numbers between 1 and" + num + "is: " + sum);
}
}
I wrote this code to sum up the odd numbers from 1 to a number entered.
Now, when I entered 8, I got the output as 24, against the desired output 16.
Can you tell me what went wrong?
You are incrementing the variable before performing summation .
while (i<=num) {
sum +=i;
i += 2;
}
You should add i to sum before adding to 2 to i. Thus, once i goes past num, the while loop will no longer execute.
import java.util.Scanner;
public class OddSum {
public static void main(String[] args) {
int num;
int i = 1;
int sum = 0;
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
num = input.nextInt();
input.close();
while (i<=num) {
// add i to sum before adding 2 to i
sum += i;
i += 2;
}
System.out.println("The sum of odd numbers between 1 and" + num + "is: " + sum);
}
Lets debug the code together:
after taking the number it would go to i<=num that while condition. Great, Then instead of getting sum it would + again 2 which cause 3. So what's happen? First case, 1 is not added before and first iteration value 1 is lose. That means whenever, you enter the loop. It goes increases before adding the previous value. So, rewrite the code this way:
while (i<=num) {
sum +=i;
i += 2;
}
You may use for instead:
for(int i=1;i<=num;i+=2){
sum +=i;
}
You're incrementing i before you sum it, instead of afterwards:
while (i <= num) {
sum +=i;
i += 2;
}
It's worth noting, though, that these kind of issues, where the loop variable is incremented by a constant, are often more convenient to write with a for loop:
for (int i = 1; i <= num; i += 2) {
sum += i;
}
Or better yet, if you're using Java 8, by collecting a stream:
int sum = IntStream.rangeClosed(1, num).filter(i -> i % 2 != 0).sum();
The reason why the result for your example with N = 8 gives 24 is because when i reaches value 7, the loop is continued and is added the value 9 to your sum too and you forget to add the first odd number: 1, because you start over from adding directly 3 to your sum.
You can either switch the statements between each other, either use a for loop instead of while:
for(int i = 1; i <= num; i += 2) {
sum += i;
}

find divisble for a number from x to y

currently im trying to find the divisibility for a number the user inputs and the number should be divisible from x to y
example: 2520 is divisible by all numbers from 1-10.
so here is what i done so far, so clearly i coded it in a bad way, can anyone do better?
public static void main (String[] args){
Scanner kb = new Scanner(System.in);
int temp = 0,x,y,num;
System.out.println("enter the number to check for");
num = kb.nextInt();
System.out.println("enter the starting number");
x = kb.nextInt();
System.out.println("enter the ending number");
y=kb.nextInt();
while(x >= y){
System.out.println("starting num must be less then the ending num,re-enter the starting num.");
x = kb.nextInt();
System.out.println(" now enter the ending number, must be greater then the starting num");
y=kb.nextInt();
}
while ( num % x == 0 && x < y){
x++;
}
if ( x == y){
System.out.println("the number "+ num + " is divisble by this range.");
}
}
}
Write it as a helper method:
public static boolean isDivisibleByAll(int dividend, int fromDivisor, int toDivisor) {
for (int divisor = fromDivisor; divisor <= toDivisor; divisor++)
if (dividend % divisor != 0)
return false;
return true;
}
Some things to consider:
It would be more user-friendly if you accepted the integers in either order. If the first is larger than the second, just go from the second to the first. So, something like:
int swapInt;
if (x > y)
{
swapInt = x;
x = y;
y = swapInt;
}
It would be more user-friendly if you accepted the same integer for the start and end. The user might want to just check one number. (How would you change your code to do this?)
It looks like you accept any integers, including zero and negative integers. Will your program still work? If not, what would you have to change?

Java: Min/Max/Average (4 variables) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Anyone knows how to run this program using 4 variables only? I tried using 1 variable for min and max "lowhigh" but I was having a hard time figuring out where to put the statements.
int numbers[] = new int[5];
int low = 0; int high = 0;
for(int count = 0; count < numbers.length; count++){
System.out.print("Please enter a number: ");
int number=s.nextInt();
if (count == 0) {
low = number;
high=number;
} else {
if(number < high) {
high= number;
}
if(number > low){
low = number;
}
}
numbers[count] = number;
}
double ave = numbers[0]+numbers[1]+numbers[2]+numbers[3]+numbers[4]/5;
System.out.println("Highest: " +high);
System.out.println("Lowest: " +low);
System.out.println("The average of all number is: " +ave); }}
Another way to do it in Java 8.
int numbers[] = new int[5];
for(int count = 0; count < numbers.length; count++){
System.out.print("Please enter a number: ");
int number=s.nextInt();
numbers[count] = number;
}
LongSummaryStatistics statistics = Arrays.stream(numbers)
.asLongStream()
.summaryStatistics();
System.out.println("Highest: " + statistics.getMax());
System.out.println("Lowest: " + statistics.getMin());
System.out.println("The average of all number is: " + statistics.getAverage());
Looks like your logic is backwards to finding high and low. Also your average wont work because order of operations. Need parens
int numbers[] = new int[5];
int low = Integer.MAX_VALUE; int high = Integer.MIN_VALUE;
for(int count = 0; count < numbers.length; count++){
System.out.print("Please enter a number: ");
int number=s.nextInt();
if (count == 0) {
low = number;
high=number;
} else {
if(number > high) {
high= number;
}
if(number < low){
low = number;
}
}
numbers[count] = number;
}
double ave = (numbers[0]+numbers[1]+numbers[2]+numbers[3]+numbers[4])/5;
System.out.println("Highest: " +high);
System.out.println("Lowest: " +low);
System.out.println("The average of all number is: " +ave); }}
You don't have to use an array if all you're doing is finding the min, max and mean.
final int COUNT = 5; //this is just to be neat, and not needed as a variable.
int low = Integer.MAX_VALUE;
int high = Integer.MIN_VALUE;
int sum = 0;
for(int i = 0; i < COUNT; i++){
int n = s.nextInt();//or whatever
if(n > high)
high = n;
if(n < low)
low = n;
sum += n;
}
System.out.println("Max: " + high);
System.out.println("Min: " + low);
System.out.println("Average: " + ((double) sum) / COUNT);
Based on what you mean by 4 variables, this may or may not work. final int COUNT is not really required and 5 can be put in directly instead.
This answer likely goes well beyond the scope of the question, but since the requirements/restrictions are not listed in full, it may still be a valid answer.
With a super strict interpretation of "4 variables", even the Scanner variable s counts.
Using streams, it can be done with 3 variables:
Scanner s; // variable 1
List<Double> values; // variable 2
String line; // variable 3
s = new Scanner(System.in);
values = new ArrayList<>();
while (true) {
System.out.print("Please enter a numbers, or press enter when done: ");
if ((line = s.nextLine().trim()).isEmpty())
break;
values.add(Double.valueOf(line));
}
if (values.isEmpty())
return;
System.out.println("Minimum: " + Stream.of(values.toArray(new Double[values.size()]))
.mapToDouble(Double::valueOf)
.min().getAsDouble());
System.out.println("Maximum: " + Stream.of(values.toArray(new Double[values.size()]))
.mapToDouble(Double::valueOf)
.max().getAsDouble());
System.out.println("Average: " + Stream.of(values.toArray(new Double[values.size()]))
.mapToDouble(Double::valueOf)
.sum() / values.size());
Sample output
Please enter a numbers, or press enter when done: 10
Please enter a numbers, or press enter when done: 42
Please enter a numbers, or press enter when done: 19
Please enter a numbers, or press enter when done: 88
Please enter a numbers, or press enter when done: 1
Please enter a numbers, or press enter when done: 3774
Please enter a numbers, or press enter when done:
Minimum: 1.0
Maximum: 3774.0
Average: 655.6666666666666
There is no point in the numbers[] array; so eliminate that.
You need a control variable for the loop, a temporary storage for the input, then three running variables for min, max and sum (average is sum devided by count, which seems to be fixed to 5).
Thats 5 variables, and you strictly need all of them. Its possible to stuff multiple values into a single variable, but I highly doubt thats what you're supposed to do.
Depending on what the requirements really are (I presume this is homework), one of the five I named above doesn't count as a variable per requirement (most likely the loop control or the temporary input storage).
Edit: Here's a variant using multiple values encoded in one variable that works with three variables (or four if you count the scanner, which I replaced with random for my convinience):
public class HighLowAverage {
public static void main(String[] args) {
long sum = 0;
long highLow = 0x8000_0000_7FFF_FFFFL;
long countNumber = 0;
for (; (countNumber >> 32) < 5; countNumber += 0x1_0000_0000L) {
countNumber = (countNumber & 0xFFFF_FFFF_0000_0000L)
| ((int) (Math.random() * 100) & 0xFFFF_FFFFL);
System.out.println(((countNumber >> 32) + 1) + ". number is: " + (int) countNumber);
sum += (int) countNumber;
if ((highLow >> 32) < (int) countNumber)
highLow = (highLow & 0xFFFF_FFFFL) | (countNumber << 32);
if (((int) highLow) > (int) countNumber)
highLow = (highLow & 0xFFFF_FFFF_0000_0000L) | (countNumber & 0xFFFF_FFFFL);
}
System.out.println("Average: " + ((double) sum) / (countNumber >> 32));
System.out.println("Min: " + (int) highLow);
System.out.println("Max: " + (highLow >> 32));
}
}
The techniques used are bit-shifting and masking to use the upper/lower half of the long datatype as independendly accessible values. Note amount of complicated expressions necessary as well as the numerous constansts in the expressions plus typecasts almost everywhere.
This is code you should never ever use - it works, but even an experienced programmer will need an excessive amount of thinking to figure out if its working correctly. My guess is that a typical beginner class teacher will have trouble understanding it at all.
Edit2: Scratch the above, it can be done with one variable. How? By replacing multiple variables with an array:
public static void main(String[] args) {
long[] vars = new long[5];
vars[1] = Long.MIN_VALUE;
vars[2] = Long.MAX_VALUE;
for (vars[0] = 0; vars[0] < 5; ++vars[0]) {
vars[4] = (int) (Math.random() * 100);
System.out.println((vars[0] + 1) + ". number is: " + vars[4]);
vars[3] += vars[4];
if (vars[4] > vars[1])
vars[1] = vars[4];
if (vars[4] < vars[2])
vars[2] = vars[4];
}
System.out.println("Average: " + ((double) vars[3]) / vars[0]);
System.out.println("Min: " + vars[1]);
System.out.println("Max: " + vars[2]);
}
Needless to say thats still confusing code. Each index of the vars array is used to hold one of the variables (0 = loop control, 1 = min, 2 = max, 3 = sum, 4 = number).
You see it all depends on what is considered a variable.

Categories

Resources