Can two non-nested for loops be condensed into one? - java

I have a sample question where we are required to find multiples of 10 between two numbers. Here's the code I've written, and although it works, is there a better way to write this code?
Scanner keyboard = new Scanner(System.in);
int value = keyboard.nextInt();
int limit = keyboard.nextInt();
int div = 10;
for (;div<value;div+=10)
System.out.print("");
for (;div<=limit;div+=10)
System.out.println(div);
keyboard.close();
The first for loop irks me. Any suggestions?

System.out.print("") does nothing, so your first loop can be re-written as:
int div = 10;
for (; div < value; div += 10)
;
The effect of that code is that div is the value of value rounded up to the nearest multiple of 10. This can be calculated as follows, using int math (where division by 10 rounds down):
int div = (value + 9) / 10 * 10;
The original code will result in a minimum value of 10, so if value <= 0 the formula will calculate incorrectly. We can use a ternary conditional operator to account for that:
int div = (value <= 10 ? 10 : (value + 9) / 10 * 10);
So, the abbreviated version of your code becomes:
Scanner keyboard = new Scanner(System.in);
int value = keyboard.nextInt();
int limit = keyboard.nextInt();
for (int div = (value <= 10 ? 10 : (value + 9) / 10 * 10); div <= limit; div += 10)
System.out.println(div);
keyboard.close();

Using java-8 :
IntStream.rangeClosed(value, limit).filter(i -> i % 10 == 0).forEach(System.out::println);
Here value is the begin index and limit is the ending index.

Related

Java:Three digit Sum - Find out all the numbers between 1 and 999 where the sum of 1st digit and 2nd digit is equal to 3rd digit

Problem statement: Three digit sum - Find all the numbers between 1 and 999 where the sum of the 1st digit and the 2nd digit is equal to the 3rd digit.
Examples:
123 : 1+2 = 3
246 : 2+4 = 6
Java:
public class AssignmentFive {
public static void main(String[] args) {
int i=1;
int valuetwo;
int n=1;
int sum = 0;
int valuethree;
int valueone = 0;
String Numbers = "";
for (i = 1; i <= 999; i++) {
n = i;
while (n > 1) {
valueone = n % 10;/*To get the ones place digit*/
n = n / 10;
valuetwo = n % 10;/*To get the tens place digit*/
n = n / 10;
valuethree = n;/*To get the hundreds place digit*/
sum = valuethree + valuetwo;/*adding the hundreds place and
tens place*/
}
/*Checking if the ones place digit is equal to the sum and then print
the values in a string format*/
if (sum == valueone) {
Numbers = Numbers + n + " ";
System.out.println(Numbers);
}
}
}
}
I got my result :
1
10
100
1000
10000
100000
1000000
10000000
100000000
1000000000
10000000001
100000000011
1000000000111
10000000001111
100000000011111
1000000000111111
10000000001111111
100000000011111111
1000000000111111111
Process finished with exit code 0
The result is not showing the actual result like it should be which should show values like: 123, 246 (Please refer to the problem statement above.)
Please let me know what seems to be the issue with the code and how to tweak it.
Don't know what you're trying to do with that while loop, or why you are building up a space-separated string of numbers.
Your code should be something like:
for (int n = 1; n <= 999; n++) {
int digit1 = // for you to write code here
int digit2 = // for you to write code here
int digit3 = // for you to write code here
if (digit1 + digit2 == digit3) {
// print n here
}
}
So basically your question is how to calculate the numbers, right?
My first hint for you would be how to get the first, second and third value from a 2 or 3 digit number.
For example for 3 digits you can do int hundretDigit = (n - (n % 100)) % 100. Of course this is really inefficient. But just get code working before optimizing it ;)
Just think about a way to get the "ten-digit" (2nd number). Then you add them and if they equal the third one you write System.out.println(<number>);
EDIT:
For 2 digit numbers I will give you the code:
if(i >= 10 && i <= 99) {
int leftDigit = (i - (i % 10)) / 10;
if(leftDigit == (i % 10)) {
//Left digit equals right digit (for example 33 => 3 = 3
System.out.println(i);
}
}
Try again and edit your source code. If you have more questions I will edit my (this) answer to give you a little bit more help if you need!

How to get nearest highest multiple of 9 in java

I need something that can calculate the nearest highest multiple of 9. So for example, if I input 1 into this function it will return 9, if I input 10 into this function it will return 18 and so on.
I've tried this 9*(Math.round(number/9)) and 9*(Math.ceil(Math.abs(number/9))) but they return the nearest multiple of 9, so if you input 10 into this function it will return 9, for my purposes it will need to return 18. (There's probably a better way to say this other then "nearest highest")
If anyone can help me that will be great!
You can use this formula.
number + (9 - (number % 9))
And for the exceptional case when the number is a multiple of 9, use a condition:
int result = number % 9 == 0 ? number : number + (9 - (number % 9));
Just add one (max) 9 times and check if it is a multiple of 9 like so:
int x = 9;
int result = 0;
for (int i = x; i < 9; i++)
{
if (i % 9 == 0)
{
result = i;
break;
}
}
// result will contains the 'nearest' 'highest' or it self multiple of 9
You can try defining a multiplier whose value depends on whether number is multiple of 9 or not. Check below code:
int number = 10;
Double ceilValue = Math.ceil(number/9);
double multiplier = 0.0;
if (number % 9 == 0) {
multiplier = ceilValue;
} else {
multiplier = ceilValue + 1;
}
Double result = 9 * multiplier;
System.out.println(result);
Output:18.0

Reverse the digits of an integer [duplicate]

This question already has answers here:
Java reverse an int value without using array
(33 answers)
Closed 3 years ago.
I'm a Java beginner so please pardon me if the question seems silly but I already searched the forums but it seems like no one has my problem.
I need to reverse the digits of an integer, and my class hasn't covered while or if loops yet, so I can't use those. All answers I can find on stackoverflow use those, so I can't use those.
the input I am given is below 10000 and above 0 and the code I have written has no problem reversing the integer if the input is 4 digits (e.g. 1000 - 9999) but once the input is between 1 - 999 it creates zeroes on the right hand side but according to the answer sheets its wrong.
For example: 1534 gets turned into 4351, but
403 becomes 3040 instead of the 304 it should be, and 4 becomes 4000 instead of 4.
I've tried different things in the code but it seems to just keep giving the same answer. Or maybe I'm just missing some key mathematics, I'm not sure.
Scanner scan = new Scanner(System.in);
System.out.println ("Enter an integer:");
int value = scan.nextInt();
int digit = (value % 10);
value = (value / 10);
int digit2 = (value % 10);
value = (value / 10);
int digit3 = (value % 10);
value = (value / 10);
int digit4 = (value % 10);
String reversednum = ("" + digit + digit2 + digit3 + digit4);
System.out.println ( reversednum);
and
Scanner scan = new Scanner(System.in);
System.out.println ("Enter an integer:");
int value = scan.nextInt();
int digit = (value % 10);
int reversednum = (digit);
value = (value /10);
digit = (value % 10);
reversednum = (reversednum * 10 + digit);
value = (value / 10);
digit = (value % 10);
reversednum = (reversednum * 10 + digit);
value = (value / 10);
digit = (value);
reversednum = (reversednum * 10 + digit);
System.out.println (reversednum);
What am I doing wrong?
You can convert from int to String -> reverse String -> convert again in int.
This is a code example.
public int getReverseInt(int value) {
String revertedStr = new StringBuilder(value).reverse().toString();
return Integer.parseInt(revertedStr);
}
Your code assumes that the number can be divided by 1000, which is clearly not the case for numbers below 1000. So add some if statements:
public int reverseNumber(int n) {
// step one: we find the factors using integer maths
int s = n;
int thousands = s / 1000; // this will be 0 if the number is <1000
s = s - thousands*1000;
int hundreds = s / 100; // this will be 0 if the number is <100
s = s - hundreds*100;
int tens = s / 10; // etc.
s = s - tens*10;
int ones = s;
// then: let's start reversing. single digit?
if (n<10) return n;
// two digits?
if (n<100) {
return ones*10 + tens;
}
// etc.
if (n<1000) {
return ones*100 + tens*10 + hundreds;
}
if (n<10000) {
return ones*1000 + tens*100 + hundreds*10 + thousands;
}
// if we get here, we have no idea what to do with this number.
return n;
}
Without spoon-feeding you code (leaving the value of writing your own homework code intact)...
Although you've said you can't use a loop, I don't think there's a sane approach that doesn't use one. Your basic problem is you have hard-coded a solution that works when the number happens to have 4 digits, rather than using code that adapts to a variable length. ie, are not using a loop.
All is not lost with your code however. You have figured out the essence of the solution. You just need to convert it to work processing one digit at a time. Consider using recursion, that divides the number by 10 each time and continues until the number is zero. Of course, you’ll have to capture the end digit before it’s lost by division.
Pseudo code may look like:
pass in the number and the current result
if the number is 0 return result
multiply result by 10 and add remainder of number divided by 10
return the result of calling self with number divided by 10 and result
then call this passing number and zero
Using modulus and division:
int nbr = 123; // reverse to 321 or 3*10*10 + 2*10 + 1
int rev = 0;
while(nbr > 0) {
rev *= 10; // shift left 1 digit
int temp = nbr % 10; // get LO digit
rev += temp; // add in next digit
nbr /= 10; // move to next digit
}
Or a recursive method:
public static int reverseInt(int number, int value) {
switch(number) { // is this conditional statement allowed???
case 0:
return value;
}
value *= 10;
int lod = number % 10;
value += lod;
number /= 10;
return reverseInt(number, value);
}

Determine if an int is a palindrome in Java?

I was working on a problem on LeetCode that asks the question: determine whether an integer is a palindrome without converting the integer into a string. I am able to come up with my own algorithm to determine a palindrome but couldn't come up with one without converting the integer to a string. So I ran into this code on the Internet:
public boolean isPalindrome(int x) {
if (x < 0)
return false;
// initialize how many zeros
int div = 1;
while (x / div >= 10) {
div = div * 10;
}
while (x != 0) {
int left = x / div;
int right = x % 10;
if (left != right)
return false;
x = (x % div) / 10;
div = div / 100;
}
return true;
}
I step through the code several times to see what it was doing but I am having such a hard time understanding how this person was able to come up with this logic. Now, I know how division and modulo works. However, this part is fuzzy:
// initialize how many zeros
int div = 1;
while (x / div >= 10) {
div = div * 10;
}
I believe this person is trying to determine the decimal place?
The next snippet part of their code, I'm completely baffled as to how they came up with this. I mean ... is this some simple math trick that I'm obviously not coming up with an explanation? In simple terms, what are they doing here? How did they decide on the divisor of 10 and 100?
x = (x % div) / 10;
div = div / 100;
I appreciate any explanation to help me understand. Thanks in Advance.
v/r,
Allen
Let's take x=12321
Then
int div = 1;
while (x / div >= 10) {
div = div * 10;
}
above part makes div = 10000,
then this part makes left = 1 and right = 1, and then left and right are compared
int left = x / div;
int right = x % 10;
Then, as we move through this part
x = (x % div) / 10;
div = div / 100;
this occurs
x = (12321%10000)/10 = (2321)/10 = 232
They modulo with div, to get rid of the first digit and then they divide by 10 to remove the last digit. The first and the last digits are removed because they have already been compared. The div is divided by 100, because we remove 2 digits from 'x' at a time...the first digit and the last digit.
now, x = 232
This part makes left = 2 and right = 2, and again left and right are compared
int left = x / div;
int right = x % 10;
then, as we move through this part
x = (x % div) / 10;
div = div / 100;
this occurs
x = (232%100)/10 = (32)/10 = 3
After this, left = 3 and right = 3, they match, 'true' is returned and the loop ends.
private static boolean isPalindrome(int number) {
int temp = number;
int result = 0;
while (temp != 0) {
result = result * 10 + temp % 10;
temp /= 10;
}
return number == result;
}

Java: round to nearest multiple of 5 (either up or down)

I need to round a number to nearest multiple of 5 (either up or down). For example, here are the list of numbers and the number next to it that it needs to round up/down to.
12.5 10
62.1 60
68.3 70
74.5 75
80.7 80
Numbers will only be positive.
haven't tested it, but 5*(Math.round(f/5)); should work
Nearest Multiple of 5
for Upper value
5*(Math.ceil(Math.abs(number/5)));
for Lower Value
5*(Math.floor(Math.abs(number/5)));
it gives Positive value only.
public static void main(String args[]) {
double num = 67.5;
if (num % 5 == 0)
System.out.println("OK");
else if (num % 5 < 2.5)
num = num - num % 5;
else
num = num + (5 - num % 5);
System.out.println(num);
}
Try this.
How about something like this:
return round((number/5))*5;
Gefei's solution is working, but I had to convert explicitly to double like this: 5*(Math.round((double)f/5))
There are many other solutions on this page, but I believe this is the most concise one.
To find the closest multiple of x for a given number,
let x be the multiple and num be the given number:
// The closest multiple of x <= num
int multipleOfX = x * ( num / x );
In your case:
int multipleOf5 = 5 * ( num / 5 );
In case you have an integer as input, otherwise the accepted answer will round it to down.
int value = 37;
value = (int) ( Math.round( value / 5.0 ) * 5.0 );

Categories