Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
So I came across this code on the web and I am trying to wrap my head around how the code is reversing the number order. Can someone help me out? Additionally, is there a way I can change the while loop into a for loop? I don't see an increment so the code is throwing me off just a little.
import java.util.Scanner;
class Challenge{
public static void main(String args[]){
///{write you code here
int n, reverse = 0;
System.out.println("Enter the number to reverse");
Scanner in = new Scanner(System.in);
n = in.nextInt();
while( n != 0 )
{
reverse = reverse * 10;
reverse = reverse + n%10;
n = n/10;
}
///}
System.out.println("Reverse is :"+reverse);
}
}
Say your number is 123. The first time through the loop, reverse starts off at 0, so this line, does nothing.
reverse = reverse * 10;
This line, however, takes the last digit of n.
reverse = reverse + n%10;
So now, reverse is 3.
The last line, divides n by 10, discarding any remainder
n = n/10;
So now n is 12.
The second pass through the loop, the following happens:
reverse = reverse * 10;
reverse is now 30.
reverse = reverse + n%10;
reverse is now 32.
n = n/10;
n is now 1.
Last time through the loop:
reverse = reverse * 10;
reverse is now 320.
reverse = reverse + n%10;
reverse is now 321.
n = n/10;
n is now 0.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I came across this algorithm on a coding site (There was no author's information) which counts all prime numbers less than a given limit. It looks very similar to SoE algorithm but it is different in the way it counts the primes:
public int countPrimes(int n) {
if (n < 3) return 0;
boolean[] s = new boolean[n];
int c = n / 2;
for (int i = 3; i < Math.sqrt(n); i += 2) {
if (s[i]) continue;
for (int j = i * i; j < n; j += 2 * i) {
if (!s[j]) {
c--;
s[j] = true;
}
}
}
return c;
}
It sets the initial count to half the limit then decrement it, but I can not seem to understand why does this work. Can anyone please explain?
First of all, the boolean array s represents SoE.
The first loop iterates odd numbers from 3 to sqrt(n) (Because all even except 2 is not prime).
At the 6th line, If i is already in the s, continue to next odd number. If not, add all multiple of i that is less or equal to n to s in the second loop.
In addition, the second loop starts from i*i because all multiple of i smaller than i*i are already checked in prior loops.
The count is initialized to n/2 because all even numbers (except 2) are not primes.
And then the loop below can start checking from multiples of 3.
If a new non-prime is found (!s[j]), the count of primes (c) is decreased.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
So I was trying to make the following program:
The user gives two integers as an input (first and last). The program is supposed to give the sum between those two numbers, but when I run the program I don't get an output. However, when I put for the first input a bigger integer than the last input, I get the first input as result. This is my code:
public class TheSumBetweenTwoNumbers {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("First: ");
int first = Integer.parseInt(reader.nextLine());
System.out.println("Last: ");
int last = Integer.parseInt(reader.nextLine());
int sum = 0;
while (first <= last); {
sum += first;
first++;
}
System.out.println("The sum is: " + sum);
}
}
your while loop runs without making a change to the block that it contains. you have closed the while loop before it even enters the block.
while (first <= last) {
sum += first;
first++;
}
try this
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I am in a intro to Java class. I seem to be having trouble figuring out the algorithm for how i want to go about this.
Currently I need to create and application that generates the number to store in an array element by summing its index and the individual digits of the index. For example, the element with index 17 should be stored as 25... (17+1+7=25) and an element with index 2 would store as 4 (2+0+2=4). I need the program to have 101 elements and then display each value.
I seem to be having trouble figuring out the algorithm for how i want to go about this. Any assistance in the matter would be greatly appreciated.
Thanks in advance. I currently am still researching this matter and am still learning to code so please bear with me.
This is the updated code that I have come up with so far
import java.util.Random;
public class Java_Lab_4 {
public static void main(String[] args) {
int size = 101;
int max = 101;
int[] array = new int[size];
int loop = 0;
Random generator = new Random();
//Write a loop that generates 101 integers
//Store them in the array using generator.nestInt(max);
generator.nextInt(max);
for (int i = 0; i<101; i++)
{
generator.nextInt(max);
}
}
There are surely many ways to achieve this, but the easiest would be repeated division by 10 (another way would be modular arithmetic, taking the index modulo 10).
This means that you would arrive at something like the following algorithm:
int n = i; // i is the index of the current item
while (n > 0) {
int x = n;
if (x > 10) { // we need to deal with the case where i is small
x = n / 10;
}
while (x > 10) { // necessary because we may be dealing with an index > 100
x = x / 10;
} // at this point we have the first digit of the index
a[i] += x; // add this digit to a[i]
n = n / 10; // get rid of the above digit in the calculation. Note that if n < 10, integer division means that n / 10 == 0
} // at the end of this loop, we have added all digits of i to a[i]
a[i] += i; / now we only need to add the index value itself
There are many ways to solve this, and this is a very straightforward and basic approach. I've added ample comments, but please try to work through the code to understand why this works rather than just copying it.
Without posting complete code -- because this is an assignment -- here are some things to consider:
array[a] = a + a;
would give you the solution for indices where a < 10. For two/three digit indices, you need to extract the digits with for example
int nthDigit = Integer.parseInt( // Finally, converts the single-char String to an int
String.valueOf( // converts the char matching the digit to a String
String.valueOf(a).charAt(n))); // converts 'a' first to a String and
// then takes its 'n'th character
where n is 0, 1 or 2. The values of these would then need to be added to the value of the index (a).
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 8 years ago.
Improve this question
Can someone explain to me how to store the previous two fibbonnaci numbers it would help alot in this problem.
public static void main(String[] args) {
int k = 0;
for (int x = 1; x < 13; x++) {
if (k > 2) {
k = (k - 1) + (k - 2);
}
System.out.print(k+" ");
k++;
}
}
when you got number 5 as the printed out put you will set k++ , that will make k=6.
after that k = (k - 1) + (k - 2); output k = (6-1)+(6-2) = 5+4 = 9 , (note : the next should be 8 so your algorithm is wrong)
You have mistaken the Idea of Fibonacci numbers.
the nth Fibonacci number is equal to the sum of previous two Fibonacci numbers. not to the (Fn-1)+(Fn-2)
Edited :
So as you can see if we know the first 2 Fibonacci numbers we can calculate the third by adding those two. and the fourth one will be the summation of second one and third one and it goes ..... to n.
Okay here is a way that you don't need a recursive approach ( you need to store the found Fibonacci numbers in an Array)
okay assume you want to find first n Fibonacci numbers. then create an array of size n and set first and second elements to one (1) since first two Fibonacci numbers are 1 and 1. now loop through the array from 2 to n. at each iteration add the previous two element to the next element.
go through the code. you will find it very easy to do.
public static void fib(int n){
int Fibonacci [] = new int[n];
Fibonacci [0]=1;
Fibonacci [1]=1;
for (int i = 2; i < n; i++) {
Fibonacci [i]=Fibonacci [i-1]+Fibonacci [i-2];
}
System.out.println(Arrays.toString(Fibonacci ));
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
There was an online coding event yesterday on Codechef, and I can't figure out how to solve one of the questions from it. Briefly put:
Given a list of N numbers { a1, a2, …, aN }, find the range [L, R] (1 ≤ L ≤ R ≤ N) that maximizes the sum (a1 + … + aL−1) − (aL + … + aR) + (aR+1 + … + aN).
In other words, you get to multiply a subsection of the list by −1, and want to maximize the sum of the resulting list.
I looked at few of the solution like this but couldn't figure out what this guy is doing.
How would I go about this?
EXAMPLE
-2 3 -1 -4 -2
Now you can multiply the subsection 3 to 5 by -1 to get
-2 3 1 4 2
such that the sum(-2,3,1,4,2) = 8 which is the maximum possible for this case
if we can find the minimum sequence from the array than that part if we multiply with one will give you max sum.
For example in this example : -2 3 -1 -4 -2 the minimum sequence is -1, -4, -2. if we multiply this sequence with one it will maximise the sum. So the question is how to find minimum sum sequence.
Here come the O(N) solution:
negate every number
and run the kadane's algorithm
If the array contains all +ve than no subarray which needs to be multiplied by -1. Check the below question. minimum sum subarray in O(N) by Kadane's algorithm
The algorithm you have shown basically calculates the maximum sum and current sum up to any element.
Note: It builds the array with opposite sign of the original elements.
If the current sum is negative, then it rejects the original sum and starts a new sum with the new element.
If the current sum is positive, then that means including the previous entries is beneficial and it adds the current element to the sum.
If I understand your problem correctly, it sounds like you want to first find the minimum subarray and then multiply that by -1 and add the remaining non negated values.
The minimum subarray is essentially the opposite of maximum subarray problem:
public class MaxSumTest {
public static class MaxSumList{
int s=0, e=0;
List<Integer> maxList;
public MaxSumList(List<Integer> l){
//Calculate s and e indexes
minSubarray(l);
//Negate the minSubarray
for(int i=s; i < e; i++)
l.set(i, -l.get(i));
//Store list
maxList = l;
}
public int minSubarray(List<Integer> l){
int tmpStart = s;
int currMin = l.get(0);
int globalMin = l.get(0);
for(int i=1; i<l.size(); i++){
if(currMin + l.get(i) > 0){
currMin = l.get(i);
tmpStart = i;
}
else{
currMin += l.get(i);
}
if(currMin < globalMin){
globalMin = currMin;
s = tmpStart;
e = i+1;
}
}
return globalMin;
}
}
public static void main(String... args){
MaxSumList ms = new MaxSumList(Arrays.asList(new Integer[]{-2, 3, -1, -4, -2}));
//Prints [-2, 3, 1, 4, 2]
System.out.println(ms.maxList);
}
}