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
Related
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.
i'm trying to print the reverse of a given integer. the function must take in an integer and return an integer (w/o recursion or printing each number as a string individually). this is what I've got but it's not working:
class Solution {
public int reverse(int x)
{
String numStr = "";
while (x > 0)
{
numStr = numStr + Integer.toString(x % 10);
x /= 10;
}
return Integer.parseInt(numStr);
}
}
i'm getting a runtime error for my return statement. Any help or advice is greatly appreciated!
You don't need a String here, just accumulate each digit and multiply the current value by 10 (to shift right). Also, your method can be static. Like,
public static int reverse(int x) {
int r = 0;
while (x > 0) {
r = (r * 10) + (x % 10);
x /= 10;
}
return r;
}
You are getting a error for the value 0. Java can´t parse string "" to a int. Initialize the string value to "0".
On the other hand, you can simplify the method:
class Solution {
public int reverse(int x)
{
String digitsChain = Integer.toString(x);
return Integer.valueOf(StringUtils.reverse(digitsChain));
}
}
You missed the case when x is 0. If x is 0, the string will be empty. When you call return Integer.parseInt(numStr), where numStr is empty string, it will cause the error.
So, if you add an if statement to check the edge case, it should be fine
public static int reverse(int x)
{
if(x == 0) return 0;
String numStr = "";
while (x > 0)
{
numStr = numStr + Integer.toString(x % 10);
x /= 10;
}
return Integer.parseInt(numStr);
}
class Solution {
public static int reverse(int x)
{
String numStr = "";
while (x > 0)
{
numStr = numStr + Integer.toString(x % 10);
x /= 10;
}
return Integer.parseInt(numStr);
}
public static void main(String[] args) {
int answer = reverse(12345);
System.out.print(answer);
}
}
I just made your method static and your code is working fine for me giving the following output:
54321
Process finished with exit code 0
I am a beginner java and trying to solve tricky problem
input=777
output should be 3
7+7+7=21 , 2+1=3;
From the above code if my input is 333 I am getting 9 as answer but when the sum is two digits(777=21) i am getting blank!
public static void main(String[] args)
{
int y=333;//if y is 777 i am getting blank
int sum=0;
String s;
char []ch;
do
{
s=String.valueOf(y);
ch=s.toCharArray();
if(ch.length>1)
{
for(int i=0;i<ch.length;i++)
{
sum+=Character.getNumericValue(ch[i]);
}
}
else
{
System.out.println(sum);
}
y=sum;
}while(ch.length>1);
}
your code maybe loop forever
the right solution is the following below
public static void main(String[] args) throws ParseException {
int y = 777;// if y is 777 i am getting blank
int sum = 0;
String s;
char[] ch;
do {
sum = 0;
s = String.valueOf(y);
ch = s.toCharArray();
if (ch.length > 1) {
for (int i = 0; i < ch.length; i++) {
sum += Character.getNumericValue(ch[i]);
}
} else {
System.out.println(ch[0]);
break;
}
y = sum;
} while (ch.length > 1);
}
Maybe the better choice is the following code
public static void main(String[] args) throws ParseException {
int y = 333;// if y is 777 i am getting blank
int sum = 0;
while (y % 10 != 0) {
sum += y %10;
y = y / 10;
if (0 == y && sum >= 10) {
y = sum;
sum = 0;
}
}
System.out.println(sum);
}
hope that helped
For a task like this, it is best practise to use recursion.
The workflow in pseudocode would look like this:
procedure sumTillOneDigit(n)
split n into it's digits
s := sum of all digits of n
if s has more than one digit:
sumTillOneDigit(s)
else
output s
I am intentionally writing this in pseudocode, since this should help you solving the task. I will not give you a Java implementation, as it looks like a homework to me.
For more information see:
https://en.wikipedia.org/wiki/Recursion_(computer_science)
http://introcs.cs.princeton.edu/java/23recursion/
You are getting that because you put the print statement in else condition..
Also note that to reset your sum value before reusing it. I.e. Set sum=0 at the start of do loop.
EDIT : there are two solutions to print you value
1. Don't put you print statements inside else conditions
Print sum outside the do while loop
First of all you must reset the value of sum variable.
and secondly you must print s in else condition and not the sum and rest is fine.
public static void main(String[] args)
{
int y=333;//if y is 777 i am getting blank
int sum;
String s;
char []ch;
do
{
sum=0;
s=String.valueOf(y);
ch=s.toCharArray();
if(ch.length>1)
{
for(int i=0;i<ch.length;i++)
{
sum+=Character.getNumericValue(ch[i]);
}
}
else
{
System.out.println(s);
}
y=sum;
}while(ch.length>1);
}
I think your solution has wrong basics. There is no point to convert your number to String and handle this as char array. You are doing too much unnecessary operations.
You can do is simpler if you stick with numbers.
You can do it using recursion:
public static int sumRec(int number){
if (number<10){
return number;
}
int sum = 0;
while(number!=0){
sum += number %10;
number /= 10;
}
return sumRec(sum);
}
or itteration
public static int sumIt(int number){
while(number>=10){
int sum = 0;
while(number!=0){
sum += number %10;
number /= 10;
}
number = sum;
}
return number;
}
it is much simpler, right?
You can solve this by 1 line:
public static int sumDigits(int n) {
return (1 + ((n-1) % 9);
}
For example: input 777--> return 1 + ( (777-1) % 9) = 3
Also can work with negative number.
Recursive variant
public static int myFunction(int num){
if(num/10 == 0){
return num;
}
int digitSum = num%10 + myFunction(num/10);
if(digitSum/10 == 0){
return digitSum;
}
return myFunction(digitSum);
}
public static int sum_of_digits(int n) {
return --n % 9 + 1;
}
This is my program
// ************************************************************
// PowersOf2.java
//
// Print out as many powers of 2 as the user requests
//
// ************************************************************
import java.util.Scanner;
public class PowersOf2 {
public static void main(String[] args)
{
int numPowersOf2; //How many powers of 2 to compute
int nextPowerOf2 = 1; //Current power of 2
int exponent= 1;
double x;
//Exponent for current power of 2 -- this
//also serves as a counter for the loop Scanner
Scanner scan = new Scanner(System.in);
System.out.println("How many powers of 2 would you like printed?");
numPowersOf2 = scan.nextInt();
System.out.println ("There will be " + numPowersOf2 + " powers of 2 printed");
//initialize exponent -- the first thing printed is 2 to the what?
while( exponent <= numPowersOf2)
{
double x1 = Math.pow(2, exponent);
System.out.println("2^" + exponent + " = " + x1);
exponent++;
}
//print out current power of 2
//find next power of 2 -- how do you get this from the last one?
//increment exponent
}
}
The thing is that I am not allowed to use the math.pow method, I need to find another way to get the correct answer in the while loop.
Powers of 2 can simply be computed by Bit Shift Operators
int exponent = ...
int powerOf2 = 1 << exponent;
Even for the more general form, you should not compute an exponent by "multiplying n times". Instead, you could do Exponentiation by squaring
Here is a post that allows both negative/positive power calculations.
https://stackoverflow.com/a/23003962/3538289
Function to handle +/- exponents with O(log(n)) complexity.
double power(double x, int n){
if(n==0)
return 1;
if(n<0){
x = 1.0/x;
n = -n;
}
double ret = power(x,n/2);
ret = ret * ret;
if(n%2!=0)
ret = ret * x;
return ret;
}
You could implement your own power function.
The complexity of the power function depends on your requirements and constraints.
For example, you may constraint exponents to be only positive integer.
Here's an example of power function:
public static double power(double base, int exponent) {
double ans = 1;
if (exponent != 0) {
int absExponent = exponent > 0 ? exponent : (-1) * exponent;
for (int i = 1; i <= absExponent; i++) {
ans *= base;
}
if (exponent < 0) {
// For negative exponent, must invert
ans = 1.0 / ans;
}
} else {
// exponent is 0
ans = 1;
}
return ans;
}
If there are no performance constraints you can do:
double x1=1;
for(int i=1;i<=numPowersOf2;i++){
x1 =* 2
}
You can try to do this based on this explanation:
public double myPow(double x, int n) {
if(n < 0) {
if(n == Integer.MIN_VALUE) {
n = (n+1)*(-1);
return 1.0/(myPow(x*x, n));
}
n = n*(-1);
return (double)1.0/myPow(x, n);
}
double y = 1;
while(n > 0) {
if(n%2 == 0) {
x = x*x;
}
else {
y = y*x;
x = x*x;
}
n = n/2;
}
return y;
}
It's unclear whether your comment about using a loop is a desire or a requirement. If it's just a desire there is a math identity you can use that doesn't rely on Math.Pow.
xy = ey∙ln(x)
In Java this would look like
public static double myPow(double x, double y){
return Math.exp(y*Math.log(x));
}
If you really need a loop, you can use something like the following
public static double myPow(double b, int e) {
if (e < 0) {
b = 1 / b;
e = -e;
}
double pow = 1.0;
double intermediate = b;
boolean fin = false;
while (e != 0) {
if (e % 2 == 0) {
intermediate *= intermediate;
fin = true;
} else {
pow *= intermediate;
intermediate = b;
fin = false;
}
e >>= 1;
}
return pow * (fin ? intermediate : 1.0);
}
// Set the variables
int numPowersOf2; //How many powers of 2 to compute
int nextPowerOf2 = 1; //Current power of 2
int exponent = 0;
/* User input here */
// Loop and print results
do
{
System.out.println ("2^" + exponent + " = " + nextPowerOf2);
nextPowerOf2 = nextPowerOf2*2;
exponent ++;
}
while (exponent < numPowersOf2);
here is how I managed without using "myPow(x,n)", but by making use of "while". (I've only been learning Java for 2 weeks so excuse, if the code is a bit lumpy :)
String base ="";
String exp ="";
BufferedReader value = new BufferedReader (new InputStreamReader(System.in));
try {System.out.print("enter the base number: ");
base = value.readLine();
System.out.print("enter the exponent: ");
exp = value.readLine(); }
catch(IOException e){System.out.print("error");}
int x = Integer.valueOf(base);
int n = Integer.valueOf(exp);
int y=x;
int m=1;
while(m<n+1) {
System.out.println(x+"^"+m+"= "+y);
y=y*x;
m++;
}
To implement pow function without using built-in Math.pow(), we can use the below recursive way to implement it. To optimize the runtime, we can store the result of power(a, b/2) and reuse it depending on the number of times is even or odd.
static float power(float a, int b)
{
float temp;
if( b == 0)
return 1;
temp = power(a, b/2);
// if even times
if (b%2 == 0)
return temp*temp;
else // if odd times
{
if(b > 0)
return a * temp * temp;
else // if negetive i.e. 3 ^ (-2)
return (temp * temp) / a;
}
}
I know this answer is very late, but there's a very simple solution you can use if you are allowed to have variables that store the base and the exponent.
public class trythis {
public static void main(String[] args) {
int b = 2;
int p = 5;
int r = 1;
for (int i = 1; i <= p; i++) {
r *= b;
}
System.out.println(r);
}
}
This will work with positive and negative bases, but not with negative powers.
To get the exponential value without using Math.pow() you can use a loop:
As long as the count is less than b (your power), your loop will have an
additional "* a" to it. Mathematically, it is the same as having a Math.pow()
while (count <=b){
a= a* a;
}
Try this simple code:
public static int exponent(int base, int power) {
int answer = 1;
for(int i = 0; i < power; i++) {
answer *= base;
}
return answer;
}
I want to split my int value into digits. eg if the no. is 542, the result should be 5,4,2.
I have 2 options.
1) Convert int into String & then by using getCharArray(), i can have separate characters & then i will convert them back into int values.
2) Convert int into String, without converting it into char array, iterate it & get all digits.
Is there any other way to solve the problem. If not, which of the option will be fast?
List<Integer> digits(int i) {
List<Integer> digits = new ArrayList<Integer>();
while(i > 0) {
digits.add(i % 10);
i /= 10;
}
return digits;
}
Use the mod 10 rule...
List<Integer> digits = new ArrayList<Integer>();
while (n > 0) {
digits.add(n%10);
n/=10;
}
int num = 542;
if (num<0) num=-num; // maybe you'd like to support negatives
List<Integer> digits = new LinkedList<Integer>();
while (num>0) {
digits.add(0, num%10);
num=num/10;
}
System.out.println(Arrays.toString(digits.toArray())); // [5, 4, 2]
divide by ten and get remainders, put them in a collection/array of your choice, keep doing this until there the quotient is zero and all you have is a remainder
You could use a Stack instead of an ArrayList if the ordering was a big issue. When popped the digits off the stack you would get them in the correct order, with the most significant digit first.
int digits(int i) {
int num=0;
while(i > 0) {
num *= 10;
num += i % 10;
i /= 10;
}
return num;
}
This will split the digits for you. Now put them into an array instead of printing them out and do whatever you want with the digits. If you want to add them, you could replace the System.out with something like sum += z;.
public class Splitter {
public static int numLength(int n) {
int length;
for (length = 1; n % Math.pow(10, length) != n; length++) {}
return length;
}
public static void splitNums(double x){
double y, z, t = x;
for (int p = numLength((int)x)-1; p >= 1; p--){
y = t % Math.pow(10, (numLength((int)(t))-1));
z = ((t - y)/Math.pow(10, p));
t = t - (z * Math.pow(10, p));
System.out.println(Math.abs((int)(z)));
}
System.out.println(Math.abs((int)(t)));
}
}
This algorithm will split primitive "int" into single digits. It starts from the last digit up to the first one.
class IntegerSplitterDemo {
static boolean digitChoper(int num) {
for(int i = 10; i <= Integer.MAX_VALUE; i *= 10 ) {
//Starts from the last digit so it will display the int in reverse order
int remainder = (i == 10) ? num % 10 : (num % i / (i /10));
//You can store the remainder value into ArrayList
System.out.print(remainder + " ");
//stop iterating the loop
if(num % i == num) { break; }
}
System.out.println("");
return true;
}
public static void main(String[] args) {
int[] num = {0, 371, 372, 678, 432, 569, 341, 371, 567, 2569874};
for(int number : num) {
digitChoper(number);
}
} // end main
}