I am a very new student. I have a coding exercise that I've been trying to get through, and I thought my solution was functional, but I am getting unexpected results. I'm wondering if there is a problem with my logic?
Assignment: Write a method named sumFirstAndLastDigit with one parameter of type int called number.
The method needs to find the first and the last digit of the parameter
number passed to the method, using a loop and return the sum of the
first and the last digit of that number.
If the number is negative then the method needs to return -1 to
indicate an invalid value.
Example input/output
sumFirstAndLastDigit(252); → should return 4, the first digit is 2 and the last is 2 which gives us 2+2 and the sum is 4.
sumFirstAndLastDigit(257); → should return 9, the first digit is 2 and the last is 7 which gives us 2+7 and the sum is 9.
sumFirstAndLastDigit(0); → should return 0, the first digit and the last digit is 0 since we only have 1 digit, which gives us 0+0 and the
sum is 0.
sumFirstAndLastDigit(5); → should return 10, the first digit and the last digit is 5 since we only have 1 digit, which gives us 5+5 and the
sum is 10.
sumFirstAndLastDigit(-10); → should return -1, since the parameter is negative and needs to be positive.
NOTE: The method sumFirstAndLastDigit needs to be defined as public
static like we have been doing so far in the course.
NOTE: Do not add a main method to solution code.
Here is what I came up with (I've included just the method itself):
public static int sumFirstAndLastDigit (int number) {
if (number < 0) {
return -1;
} else if (number <= 9) {
number += number;
return number;
}
int num = number;
int sumFirstAndLast = 0;
while (num > 0) {
int useDigit = (num % 10);
if ((num == number) || ((double)num < 1)) {
sumFirstAndLast += useDigit;
}
num = num / 10;
} return sumFirstAndLast;
}
I think the issue might be the if statement in my while loop - but I'm not sure. I want it to check if num is equal to the original number that gets passed to the method, and check after num has been run through the while loop a few times, check if it's less than 1 (which is why I cast it as a double)
When I write out how each loop should run, it seems like it would work, but I've been getting incorrect output.
Any help, critiques, rules of thumb, etc. are greatly appreciated. Thanks in advance.
You can do something like this
public static int sumFirstAndLastDigit (int number) {
int first = number;
while (first >= 10) {
first /= 10;
}
int last = number % 10;
return (first + last) >= 0 ? (first + last) : -1;
}
It gets frist and last number from the input and sums them together, then in the return you check if it was a negative number, then you return -1.
Related
The code below has no output when I run it, I think somehow it is infinite loop? How to fix it?
Write a method named getEvenDigitSum with one parameter of type int called number.
The method should return the sum of the even digits within the number.
If the number is negative, the method should return -1 to indicate an invalid value.
EXAMPLE INPUT/OUTPUT:
getEvenDigitSum(123456789); → should return 20 since 2 + 4 + 6 + 8 = 20
getEvenDigitSum(252); → should return 4 since 2 + 2 = 4
getEvenDigitSum(-22); → should return -1 since the number is negative
public class getEvenDigitSum {
public static int getEvenDigitSum(int number) {
int sum = 0;
int lastDigit=0;
if (number < 0) {
return -1;
}
while (number >0) {
lastDigit = number % 10;
if (number % 2 == 0)
{
sum += lastDigit;
number = number / 10;
}
}
return sum;
}
}
while (number >0) {
lastDigit = number % 10;
if (number % 2 == 0)
{
sum += lastDigit;
number = number / 10;
}
}
OK, and what happens if the number isn't even? You didn't make an else/else if statement after; if your number is odd, it stays the same, the loop is infinite, and hence your code does nothing.
Your condition only handles even digits, but think about what happens when you get a number that contains odd digit, like 1221 for example.
Try adding the missing else statement:
while (number >0) {
lastDigit = number % 10;
if (number % 2 == 0)
{
sum += lastDigit;
number = number / 10;
}
else {
// Deal with odd digit, leaving for you to implement
{
}
General tip: The best way to find errors in your code is to write tests and debug your code.
These are two skills every developer should poses and practice regularly
I tried to write a method (for kicks) that would sum up the digits at even places using Java recursion.
For example, the number 23495 would return 3+9 = 12.
I am unsuccessful and would appreciate hints or what I'm doing wrong.
int sumEven = 0;
int sumOdd = 0;
int i = 1;
if (n == 0)
return sumEven;
if (n != 0) {
if (i % 2 == 0)
{
i++;
sumEven += n % 10;
}
else
{
i++;
sumOdd += n % 10;
}
}
return sumEven + getEven (n/=10);
The problem is you're trying to do too much - take a look at my comment on the Q
A recursive method needs an input that contains everything it needs to work with, a return value, and an execution path where it calls itself until something happens that means it doesn't need to call itself any more - without this bit it will recourse until it overflows the stack
int sumEveryOtherDigit(int input){
if(input >= 100)
return input%10 + sumEveryOtherDigit(input/100);
else
return input%10;
}
This takes the input , and if there is any point to running again (if the input is at least 100) takes the rightmost digit plus running itself again with a smaller number
Eventually the number gets so small that there isn't any point running itself again so it just returns without running itself again and that is how the recursion stops
Now from your comment on another answer it seems you want to determine even and odd as working from the left so we need to either start with the number (1630) or the number divided by ten (23495 -> 2349) - basically to start the recursion going we always want to pass in a number with an even number of digits
int num = 23495;
int numOfDigits = (int)Math.log10(num)+ 1;
if(numOfDigits%2==0)
result = sumEveryOtherDigit(num);
else
result = sumEveryOtherDigit(num/10);
You should iterate over the digits of the input number, and then sum the remainder mod 10 only for even position digits:
int input = 23495;
input /= 10;
int sum = 0;
while (input > 0) {
sum += input % 10; // add last even digit
input /= 100; // advance by two digits, to the next even digit
}
System.out.println("sum of even digits of input is: " + sum);
This prints:
sum of even digits of input is: 12
I do not understand why the recursion problem of this code I wrote works, below I will show what the function that is used in the code below from the library used in my university
void multiplyBy10(int k)
Multiplies this by 10 and adds k.
Parameters:
k - the int to be added
Updates:
this
Requires:
0 <= k < 10
Ensures:
this = 10 * #this + k
and divideBy10 simply divides the natural number by 10 and returns the remainder and NaturalNumber.RADIX is simply a constant equal to 10.
private static void decrement(NaturalNumber n) {
assert n != null : "Violation of: n is not null";
assert !n.isZero() : "Violation of: n > 0";
int digit = n.divideBy10();
digit = digit - 1;
if (digit == NaturalNumber.RADIX) {
digit = 0;
decrement(n);
} else if (digit < 0) {
digit = 9;
decrement(n);
}
n.multiplyBy10(digit);
}
Now the code does work, if you input any number it will decrease it by 1, although I am a bit confused as to why
First of all. Thats exactly the reason why classes like NaturalNumber should be immutable. Using a static method for applying changes on an instance is a violation of the open-closed-principle.
'int digit = n.divideBy10();' changes the value of n. Otherwise this method would not terminate.
I assume that you call 'n.multiplyBy10(-1)'. This would explain the correct result for numbers<10.
Which input arguments have you tested for this method?
The method written in the below code needs to take integer and result sum of 1st digit and last digit in the integer.
NOTE: The reason i am asking this question though i got to know the correct solution is i need to understand why my code is not working also as that makes me a better programmer please help.
public class FirstLastDigitSum {
public static int sumFirstAndLastDigit(int number)//to add first and last
//digits of a given interger
{
int firstdigit=0;
int lastdigit=0;
if(number>=0 && number<=9)
{
return number+number;
}
else if(number>9)
{
lastdigit=number%10;
while(number>0)
{
number/=10;
if(number<=9 & number>=0){
firstdigit=number;
}
}
return firstdigit+lastdigit;
}
else
return -1;
}
public static void main(String[] args)
{
System.out.println(sumFirstAndLastDigit(121));
}
}
In the above code if i keep number/=10 after if block like below
if(number<=9 & number>=0){
firstdigit=number;
}
number/=10;
then my code is giving proper results. like if i input 121 to the method as first digit is 1 and second digit is 1 it is summing both and giving me result 2. which is absolutely correct
But if keep number/=10 above the if block like below
number/=10;
if(number<=9 & number>=0){
firstdigit=number;
}
Then my code is not giving proper result it is giving only last number which is 1.
I am not at all understanding why this is happening can any one explain please.
Lets break this up into two parts. Get the last digit of the number, and getting the first digit of the number.
The first part of the problem is easy. Its exactly what you already have; just take modulo 10 of the number.
int lastdigit = number % 10;
The second part is a little trickier, but not too much. While the number is greater than 10 divide it by 10 (using integers you will have truncation for the remainder). One problem I see in your solution is that you keep checking the value even after a digit is discovered. That means if the value was 1234, you correctly find 1, but then overwrite it to 0 with an extra loop iteration
int firstdigit = number;
while (firstdigit >= 10) {
firstdigit /= 10;
}
And that's it, you are done. Just return the value.
return firstdigit + lastdigit;
If the number is less than 0 then return -1. Otherwise the last number can be found by modulus 10, and the first number found by dividing by 10 until that number is less than 10.
public static int sumFirstAndLastDigit(int number) {
if (number < 0) {
return -1;
}
int last = number % 10;
int first = number;
while (first >= 10) {
first = first / 10;
}
return first + last;
}
In this case:
while(number>0)
{
number/=10;
if(number<=9 & number>=0){
firstdigit=number;
}
}
Note that you change number after you check number > 0. That means that number can be 0 when reaches the if statement and if it is 0 it will be accepted as first digit because it satisfies the condition number<=9 & number>=0. As an example, when you test it with 121 you have this values for number 121, 12, 1 and 0. The last one satisfies the if statement and set first digit to 0.
In this case:
while(number>0)
{
if(number<=9 & number>=0){
firstdigit=number;
}
number/=10;
}
You change number before you check number > 0. That means that the if statement will never have a number = 0 and firstdigit will never be 0. As an example, when you test it with 121 you have this values for number 121, 12, and 1. The last one satisfies the if statement and set first digit to 1. After that you divide number by zero and it becomes 0 and it stop the while loop.
This is not a direct solution to your problem, but we can fairly easily handle this using regex and the base methods:
int number = 12345678;
String val = String.valueOf(number);
val = val.replaceAll("(?<=\\d)\\d+(?=\\d)", "");
number = Integer.parseInt(val);
int sum = number % 10 + number / 10;
System.out.println(sum);
I need to write a code which should calculate the first 200 prime numbers, but I can't hand it in as long as I can't explain everything. I used a piece of code from the internet as reference (http://crab.rutgers.edu/~dhong/cs325/chapter3/PrimeNumber.java).
Whole code:
public class Opdracht3 {
public static void main(String[] args) {
int limiet = 200;
int counter = 1;
int testpriem = 3;
boolean isPriem;
while (counter <= limiet) {
isPriem = true;
for (int i = 2; i <= testpriem / 2; i++) {
if (testpriem % i == 0) {
isPriem = false;
break;
}
}
if (isPriem) {
System.out.println(counter + ": " + testpriem);
counter++;
}
testpriem++;
}
}
}
Below part of code verifies if the number is a composite. If testpriem is composite, then comes out of the loop and starts over. Otherwise, it continues and prints the prime number testpriem.
The problem is here:
for (int i = 2; i <= testpriem / 2; i++) {
if (testpriem % i == 0) {
isPriem = false;
break;
}
}
I tested what happens to i, and one way or another it recognizes the divisor needed to calculate the composite. (With 4 divisor is 2, with 9 divisor is 3, with 221 divisor is 13) But I am flabbergasted as of why.
Any ideas?.
the % or ("remainder") operator in Java divides one operand by another and returns the remainder as its result. And of course if integer x is evenly divisible by another integer y (meaning x/y = some integer z with a remainder of zero), then x can not be prime.
First remember every number able to divide by its half or less. Consider number 7 it is possible divided by 1,2,3 because after 3, if try to divide number by 4 means 4x2 = 8 that is greater than 7. so it is optimum way to find divisor in this way. One more thing every number divided by 1 and number itself. so if number number is divided by 1 or itself then it is called prime so i starts from 2.
now consider testpriem =7 so you will get loop like
for (int i = 2; i <= 7 / 2(i.e 3); i++)
{
if(7 % i == 0)
{
isPriem = false;
break;
}
so first time it checks 7%2=1 so condition false. again check for 7%3 = 1 again condition false. and now this condition full fills here i <= 7 / 2(i.e 3) so loop stopped and it result 7 number is prime
Well, if testpriem % i == 0, it means that i divides testpriem, which means that testpriem is not a prime a number and i, is its first divider. % is the modulo operation, which is the rest of the division.
https://en.wikipedia.org/wiki/Modulo_operation
The break stops the for loop and moves to the next position in the while loop. So it does not restart the for loop for the current tested number.
The break is used for efficiency reasons. You could remove it and the algorithm would still work correctly but slower.