For my program, I'd want to code an array 1-100. In that array, I want to store the number + their digits. For example, if the number is 6 the stored value would be 6 because of 6 + 6 = 12. If the number is 17 the stored value should be 25 because 17 + 1 + 7 = 25. I want to do it for every number. My code has a method and 2 for loops but currently outputs everything as 0; Here's my code.
public class GeneratedNums {
public static void main(String[] args) {
int [] numbers = new int [101];
for ( int x=0; x < 101; x++){
numbers[x] = sumDigits (x);
}
for ( int x=0; x < numbers.length; x++){
System.out.println(x + ": " + numbers[x]);
}
}
public static int sumDigits ( int num) {
int sum = num;
while ( num != 0){
num += num%10;
num /= 10;
}
return num;
}
}
You should be adding the result of modulo operation to sum. And you should return sum.
while ( num != 0){
sum += num % 10;
num /= 10;
}
return sum;
You don't need these many loops, you can improve it by caching the previous outputs and reusing it (Dynamic programming tabulation). Considering you don't have values greater than 100 following code can work for you
public static int sumDigits(int num) {
int[] cache = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1 };
int sum = num + cache[num % 10] + cache[num / 10];
return sum;
}
basically, I've cached outputs for first 10 inputs.
FYI, you can make scale the program for larger inputs by storing the previous outputs in HashMap
Related
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;
}
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;
}
For this lab, you will enter two numbers in base ten and translate
them to binary. You will then add the numbers in binary and print out
the result. All numbers entered will be between 0 and 255, inclusive,
and binary output is limited to 8 bits. This means that the sum of the
two added numbers will also be limited to 8 bits. If the sum of the
two numbers is more than 8 bits, please print the first 8 digits of
the sum and the message "Error: overflow". Your program should
represent binary numbers using integer arrays, with the ones digit
(2^0) stored at index 0, the twos digit (2^1) stored at index 1, all
the way up to the 2^7 digit stored at index 7. Your program should
include the following methods:
int[] convertToBinary(int b) Translates the parameter to a binary value and returns it stored as an array of ints.
void printBin(int b[]) Outputs the binary number stored in the array on one line. Please note, there should be exactly one space
between each output 0 or 1.
int[] addBin(int a[], int b[]) Adds the two binary numbers stored in the arrays, and returns the sum in a new array of ints.
When entering my code into CodeRunner (which tests the code and returns a grade back depending on the results of each test) I cannot seem to pass one of the tests. This is the message that I am getting:
*You had 43 out of 44 tests pass correctly. Your score is 97%.
The tests that failed were: Test: addBin() method Incorrect: Incorrect number returned*
Heres my code:
import java.util.Scanner;
class Main {
public static int[] convertToBinary(int a) {
int[] bin = {0, 0, 0, 0, 0, 0, 0, 0};
for (int i = bin.length - 1; i >= 0; i--) {
bin[i] = a % 2;
a = a / 2;
}
return bin;
}
public static void printBin(int[] b) {
int z;
for (z = 0; z < b.length; z++) {
System.out.print(b[z] + " ");
}
System.out.println();
}
public static int[] addBin(int[] c, int[] d) {
int[] added = new int[8];
int remain = 0;
for (int x = added.length - 1; x >= 0; x--) {
added[x] = (c[x] + d[x] + remain) % 2;
remain = (c[x] + d[x] + remain) / 2;
}
if (added[0] + c[0] + d[0] == 1) {
added[0] = 1;
} else if ((added[0] + c[0] + d[0] == 2) || (added[0] + c[0] + d[0] == 3)) {
System.out.println("Error: overflow");
}
return added;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a base ten number between 0 and 255, inclusive.");
int num1 = scan.nextInt();
System.out.println("Enter a base ten number between 0 and 255, inclusive.");
int num2 = scan.nextInt();
int[] bin;
bin = convertToBinary(num1);
System.out.println("First binary number:");
printBin(bin);
int[] bin1 = bin;
bin = convertToBinary(num2);
System.out.println("Second binary number:");
printBin(bin);
int[] bin2 = bin;
System.out.println("Added:");
{
printBin(addBin(bin1, bin2));
}
}
}
If anyone could take a look at my code above and see if they could tell me what needs to be changed to fix the addbin() method so that it passes all of the tests, that'd be great! Any help is greatly appreciated even if you are not sure it would work! Thanks!
Hi first of all pardon my English but i guess your assignment accepts 1 and 255 too. So i added two of them and get 1 0 0 0 0 0 0 0 in your code. But i think it need to be 0 0 0 0 0 0 0 0 with an overflow error. So i changed your code a little bit.
public static int[] addBin(int[] c, int[] d) {
int[] added = new int[8];
int remain = 0;
for (int x = added.length - 1; x >= 0; x--) {
added[x] = (c[x] + d[x] + remain) % 2;
remain = (c[x] + d[x] + remain) / 2;
}
if (remain!=0) {
System.out.println("Error: overflow");
}
return added;
}
It's my first answer on the site so i hope it works for your test
The Word Problem I'm trying to solve:
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
I'm sure you've seen questions about this problem on Project Euler before, but I'm not sure why my solution doesn't work, so I'm hoping you can help!
public class Problem2Fibonacci {
public static void main(String[] args) {
/* Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. */
int sum = 0; // This is the running sum
int num1 = 1; // This is the first number to add
int num2 = 2; // This is the second number
int even1 = 0;
int even2 = 0;
int evensum = 0;
while (num2 <= 4000000){ // If i check num2 for the 4000000 cap, num will always be lower
sum = num1 + num2; // Add the first 2 numbers to get the 3rd
if(num2 % 2 == 0){ // if num2 is even
even1 = num2; // make even1 equal to num2
}
if(sum % 2 == 0){ // if sum is even
even2 = sum; // make even2 equal to sum
}
if (even1 != 0 && even2 != 0){ // If even1 and even2 both have values
evensum = even1 + even2; // add them together to make the current evensum
even2 = evensum;
}
num1 = num2;
num2 = sum;
System.out.println("The current sum is: " + sum);
System.out.println("The current Even sum is: " + evensum);
}
}
}
So my 2 questions are,
1. Why doesn't my plan to get sum of even numbers work correctly?
and
2. The last time my loop runs, it uses a num2 that is > 4000000. Why?
Thanks!
This should help you :
int first = 0;
int second = 1;
int nextInSeq =first+second;
int sum =0;
while(nextInSeq < 4000000) {
first = second;
second = nextInSeq;
nextInSeq = first + second;
if(nextInSeq % 2 ==0)
sum = sum + nextInSeq;
System.out.println("Current Sum = " + sum);
}
System.out.println("Sum = " + sum);
For your piece of code : even1 and even2 are not required and they are carrying value they hold from previous iterations as you continue.
Write a program to Round a number to the next multiple of 10 if its ones digit is 5 or more, otherwise round it the previous multiple of 10.So, 25 and 26 round to 30 where as 23 and 24 round to 20. 20 also rounds to 20. You have been given 4 ints as input. Round each of the input values and return their sum.
MyApproach
I created 2 functions in the first function I counted the sum of all 4 numbers.
In the second function I checked the UnitDigtit if>=5 &&<=9 Then proceed with set of statements given in the question.
else
I checked if Its a one digit or two or any digit number.If One digit I returned num=0 else I proceded with the sets of statements.
Sample Input #1
sumRounded(11,15,23,30)
Sample Output #1
80 (11 rounds to 10, 15 to 20, 23 to 20 and 30 to 30)
Sample Input #2
sumRounded(1,3,7,9)
Sample Output #2
20
public int sumRounded(int num1, int num2, int num3, int num4)
{
int a=checkRound(num1);
int b=checkRound(num2);
int c=checkRound(num3);
int d=checkRound(num4);
return a+b+c+d;
}
public int checkRound(int num)
{
int a=num%10;
if((a>=5) &&(a<=9))
{
if(a==5)
{
num=num+5;
}
else if(a==6)
{
num=num+6;
}
else if(a==7)
{
num=num+7;
}
else if(a==8)
{
num=num+8;
}
else if(a==9)
{
num=num+9;
}
return num;
}
else
{
if((num/10)!=0)
{
if(a==1)
{
num=num-1;
}
else if(a==2)
{
num=num-2;
}
else if(a==3)
{
num=num-3;
}
else if(a==4)
{
num=num-4;
}
return num;
}
else
{
return num=0;
}
}
}
Results:
Parameters Actual Output Expected Output
'289' '3' '25' '308' 644 630
Rounding
If the remainder is less than 5, subtract it from num. Otherwise, add ten minus the remainder to the num. Something like,
static int checkRound(int num) {
int rem = num % 10;
return rem < 5 ? num - rem : num + (10 - rem);
}
or use Math.round(float) like
static int checkRound(int num) {
return Math.round((float) num / 10) * 10;
}
Varargs
You could also implement sumRounded as a varargs method with a for-each loop
static int sumRounded(int... nums) {
int sum = 0;
for (int num : nums) {
sum += checkRound(num);
}
return sum;
}
Testing
Then you could test it like,
public static void main(String[] args) {
System.out.println(sumRounded(11, 15, 23, 30)); // == 80
System.out.println(sumRounded(1, 3, 7, 9)); // == 20
}
Simply use the reminder check inside checkRounded method
int number = 23;
int output=0;
if(number%10<5){
output=(number/10)*10;
}
else{
output=((number/10)+1)*10;
}
System.out.println(output);
You simply put following code in you chexkRound method
int a = num % 10;
if ((a >= 5) && (a <= 9)) {
num = 10 * (num / 10 + 1);
} else {
num = 10 * (num / 10);
}
return num;
If you want to fix you way do the following but Exbury's answer is a shorter way of doing it.
If you are rounding up you should add the 10 minus the number, not the number itself. So for example, 26 rounded up should be 26+(10-6) = 26+(4) = 30
Well the following code perfectly suits your need
//code starts
public static void main(String[] args) {
System.out.println("The answer is: " + getSum(2,5,19));
}
public static int getSum(int... nums) {
int sum = 0;
for (int n : nums) {
int lastDigit = n % 10;
if (lastDigit >= 5) {
sum = sum + n + (10 - (lastDigit));
} else {
sum = sum + 10 * (n / 10);
}
}
return sum;
}
//code ends