enter image description hereI am trying to solve this question:
a) Write a method with the following header that takes an integer n and
returns the value of n! (pronounced n factorial) computed as follows:
public static int factorial(int n)
Note that 0! = 1 and n! = n * (n-1) * (n-2)*.....*1.
Example: factorial(4) will return 24 which is = 4*3*2*1.
b) Write a method with the following header that takes an integer x and
returns true if x is a Strong number. Otherwise, it returns false.
public static boolean isStrongNumber(int x)
Note that the isStrongNumber method should call the factorial method to compute the factorial of
each digit in x.
public static int factorial(int n) {
int f =1;
for (int i = 1; i <=n; i++)
f=f*i;
return f;
}
public static boolean isStrongNumber(int x) {
int temp = x;
int z;
int q = 0;
int sum = 0;
while (temp > 0) {
x = x % 10;
z = factorial(x);
q += z;
if (q == temp) {
System.out.print(q + " ");
return true;
}
}
}
This is my answer, but I get an error every time I try to run it.
You did not return boolean value at end of the isStrongNumber method
public static int factorial(int n) {
int result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}
public static boolean isStrongNumber(int num) {
int originalNum = num;
int sum = 0;
while (num > 0) {
sum += factorial(num % 10);
num /= 10;
}
return sum == originalNum;
}
, main function
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int number = Integer.parseInt(scanner.nextLine());
Set<Integer> set = new TreeSet<>();
for (int i = 1; i <= number; i++) {
if (isStrongNumber(i)) {
set.add(i);
}
}
System.out.println("The Strong numbers between 1 and " + number + " are:");
System.out.println(set);
scanner.close();
}
, output for input 100000
Enter a positive integer: 100000
The Strong numbers between 1 and 100000 are:
[1, 2, 145, 40585]
This cannot compile as it lacks a return statement outside the while loop. In fact, you cant be sure to go inside the loop even once if x<=0 for exmaple. You should add return false outside the loop at the end of the method. Also if you get an error and write a question on StackOverflow, copy the error message it's very helpful.
Related
Here is my function that suppose to reverse and return giver integer:
public static int reverse(int x) {
List<Integer> digits = new ArrayList<>();
int result = 0, count = 0;
while(x != 0) {
digits.add(x % 10);
x /= 10;
count++;
}
System.out.println(digits);
int i = 0;
while(count != 0) {
result += digits.get(i) * (int) Math.pow(10, count - 1);
System.out.printf("result: %d i: %d, count: %d - ", result, i, count);
System.out.printf("%d * %d\n", digits.get(i), (int) Math.pow(10, count - 1));
count--;
i++;
}
return result;
}
I encountered a problem. For example when I pass value of 1534236469 this is what happens:
result: 410065408 i: 0, count: 10 - 9 * 1000000000
.
.
.
1056389759
Why this is happening?
Also all tips on making this function better are welcome.
Also all tips on making this function better are welcome.
A simple implementation can be as follows:
public class Main {
public static void main(String[] args) {
int x = 123456789;
int y = reverse(x);
System.out.println(x);
System.out.println(y);
}
public static int reverse(int x) {
return Integer.parseInt(new StringBuilder(String.valueOf(x)).reverse().toString());
}
}
Output:
123456789
987654321
Also, as already mentioned in the comment, when you assign a value bigger than the maximum allowed value to an int variable, the value gets converted into a value from the other end i.e. Integer.MAX_VALUE + 1 becomes Integer.MIN_VALUE. Therefore, for an integer like 1534236469 whose reverse is bigger than an int variable can hold, you should convert the reverse into a long value as shown below:
public class Main {
public static void main(String[] args) {
int x = 1534236469;
long y = reverse(x);
System.out.println(x);
System.out.println(y);
}
public static long reverse(int x) {
return Long.parseLong(new StringBuilder(String.valueOf(x)).reverse().toString());
}
}
Output:
1534236469
9646324351
Marcin, you can implement your reverse method like below,
public static long reverse(int x) {
long reverseDigit = 0;
while (x != 0) {
reverseDigit = reverseDigit * 10 + (x % 10);
x /= 10;
}
return reverseDigit;
}
I hope this helps.
A more proper way to reverse an integer would be:
int reverse(int n) {
int reversed = 0;
Boolean isNegative = n < 0;
n = Math.abs(n);
while(n > 0) {
reversed = reversed * 10 + (n % 10);
n /= 10;
}
if (isNegative)
reversed *= -1;
return reversed;
}
I think the problem could be, that the reverse of an int ist not always an int.
2147483647 is max int so,
9646324351
is too big and 1534236469 has no chance
I tried to use some codes on Stack Overflow but when I used some codes,I didn't get the answer I want, this is my code now:
public class JavaApplication7 {
public static void main(String[] args) {
boolean answer = rev(1221);
if(answer == true) System.out.println("true");
else System.out.println("false");
}
static boolean rev(int number){
int reverse = 0, remain;
int num = number;
while(number > 0){
remain = number % 10;
reverse = (reverse * 10) + remain;
num = num / 10;
}
return number == reverse;
}
}
I want to check if palindrome is equal to the orginal int.
You have two bugs relating to confusing num (the local copy which you're modifying) and number (the parameter which you don't modify). I would make it final to make clear that the value is constant. And then use num consistently. I would also simplify the code a little. Like,
static boolean rev(final int number) {
int reverse = 0;
int num = number;
while (num > 0) {
reverse *= 10;
reverse += num % 10;
num /= 10;
}
return number == reverse;
}
And similarly in main, using an if to print true or false is pointless (and if you're going to do that use if (answer) - don't add unnecessary == true). But, I would prefer,
public static void main(String[] args) {
boolean answer = rev(1221);
System.out.println(answer);
}
Which outputs
true
Your rev function should be as below.
reversedInteger = 0, remainder, originalInteger;
originalInteger = num;
while( num != 0 )
{
remainder = num % 10;
reversedInteger = reversedInteger * 10 + remainder;
num /= 10;
}
static boolean rev(int number){
int reverse = 0;
int num = number;
while(number > 0){
reverse = reverse * 10 + number % 10;
number /= 10;
}
return reverse == num;
}
This is code to find armstorm numbers between given intervals. But when I put my my method in loop in main method so that it can run between given interval, then the loop only run one time and don't change the value passed to method. Why this is so? Is there is a difference in working of these conditions in different languages?
import java.util.Scanner;
class ArmstormNumbers {
int mod, div, count = 0, rev = 0, pow = 1, sum = 0;
int checkArm(int num) {
while(num!=0) {
mod = num%10;
div = num/10;
num = div;
count++;
rev = (rev*10) + mod;
}
while(rev!=0) {
mod = rev%10;
div = rev/10;
rev = div;
int temp = mod;
for(pow = 1; pow < count; pow++) {
mod = mod * temp;
}
sum=sum+(mod);
}
return sum;
}
}
class HelloWorld {
public static void main(String args[]) {
int num, arms, inp, fp, asm, num2;
Scanner input = new Scanner(System.in);
ArmstormNumbers object = new ArmstormNumbers();
System.out.println("This program will find armstorm numbers between two intervels");
System.out.println("Input Initial point ");
num = input.nextInt();
System.out.println("Input Final Point");
num2 = input.nextInt();
int temp = num;
for(num = temp; num <= num2; num++) {
asm = object.checkArm(num);
if(asm == num) {
System.out.println(num);
}
}
}
}
Move the variable declarations so that they become method-local variables which get initialised each time the method is executed, instead of only once when instantiating the object.
I.e. change
int mod,div,count=0,rev=0,pow=1,sum=0;
int CheckArm(int num)
{
to
int CheckArm(int num)
{
int mod,div,count=0,rev=0,pow=1,sum=0;
The problem you have and which you solve that way is probably relying on sum being 0 at start but not making that sure.
The below code calculates a value which is obtained as sum of square of each digits in str. This sum is again calculate m times.
Example: m = 2, str="123"
At m=1 (1^2)+(2^2)+(3^2) = 1+4+9 = 14
At m=2 (1^2)+(4^2) = 1+16 = 17
So 17 should be the final answer for this input. For large inputs or when run against 1000 of test case like above, this code is giving time limit exceeded errors. Can this code further optimized?
Test case will be less than 1001
1 <= str.length(), m <= 10^9
public static void puzzle(int m,String str) {
int ans = 0;
while (m > 0) {
ans=0;
m--;
int j = 0;
while (j < str.length()) {
int val = Integer.parseInt(str.charAt(j) + "");
ans += val* val;
j++;
}
str = String.valueOf(ans);
}
System.out.println(ans);
}
I have tried my level best and could come up with above iterative solution. Could not improve even with a recursive solution.
Recursive Code:
public static int solve(int m, String n){
if(m < 1)
return Integer.parseInt(n);
int idx = 0;
int res = 0;
while(idx< n.length()){
int val = Integer.parseInt(n.charAt(idx) + "");
res += val*val;
idx++;
}
return solve(m-1,String.valueOf(res));
}
Don't do the operation using strings. Stay with integers.
Since you're just adding the square of digits, you can do it starting with the last digit, so a loop doing modulus and division by 10, until zero, will do the trick.
public static int puzzle(int m, String str) {
int value = Integer.parseInt(str);
for (int i = 0; i < m; i++) {
int sum = 0;
for (; value != 0; value /= 10) {
int digit = value % 10;
sum += digit * digit;
}
value = sum;
}
return value;
}
This code is designed for summing up the digits of the number but it brings up
javac Root.java Root.java:17: error: '.class' expected
Who can explain what is the problem here. Also i want to make the same program using Arrays but i have problems with putting int in Array, if you have suggestions i am glade to here you.
import java.util.Scanner;
class Root {
public static int numRoot(int n, int sum){
while (n != 0) {
sum = sum + n % 10;
n = n / 10;
}
return sum;
}
public static void main(String[] args){
int sum = 0;
Scanner in = new Scanner(System.in);
System.out.print("Enter a number here");
int n = in.nextInt();
int root = numRoot(int sum, int n);
System.out.print("the sum of the digits off given num is " + root);
}
}
You have error here, Correct it.
int root = numRoot(int sum, int n); // this is wrong
Change it to
int root = numRoot(n,sum); // should use correct order of input parameters
This should be your method, you do not need to pass sum:
public static int numRoot(int n){
int sum=0;
while (n != 0) {
sum += n % 10;
n = n / 10;
}
return sum;
}
and you shall call it like this:
int root = numRoot(n);