Convert any number to one digit number - java

Consider the number 2345.If you multiply the digits of it then you get the number 120.Now if you again multiply the digits of 120 then you will get 0 which is one digit.
import java.util.Scanner;
public class SmallestNum
{
int prod=1,sum=0;
void product(int m)
{
while(m!=0)
{
int a=m%10;
m=m/10;
prod=prod*a;
}
System.out.println(prod);
}
public static void main(String args[])
{
Scanner scn=new Scanner(System.in);
int x=scn.nextInt();
SmallestNum sn=new SmallestNum();
sn.product(x);
}
}
I can get the 120 from this code.But how can i do the same procedure with 120 and get the answer 0.Pls help me.

You can just add an other loop around your while, the end condition being prod < 10, i.e. having only one number.
void product(int m)
{
int prod;
do {
prod = 1;
while(m!=0)
{
int a = m%10;
m = m / 10;
prod *= a;
}
System.out.println(prod);
} while (prod >= 10);
}

public int reduceToOneDigit(int inputNumber){
int result = 1;
while(inputNumber > 0){
result *= (inputNumber % 10);
inputNumber /= 10;
}
if (result > 9)
result = reduceToOneDigit(result);
return result;
}
So basically: multiply the digits of your inputNumber. If the result has more than one digit (so result is > 9, at least 10) call method recursively on the result.
Alternatively, do the same without recursion, using a do-while loop:
public int reduceToOneDigitNoRecursion(int inputNumber){
int result = 1;
do{
while(inputNumber > 0){
result *= (inputNumber % 10);
inputNumber /= 10;
}
}
while(result > 9);
return result;
}

Use recurssion
void product(int m)
{
if(m%10 == 0){
return;
}
while(m!=0)
{
int a=m%10;
m=m/10;
prod=prod*a;
}
System.out.println(prod);
product(prod);//repeat the procedure
}

Recursive call the function
if(String.valueOf(prod).length()>1){
product(prod)
}
complete code
public class SmallestNum
{
int prod=1,sum=0;
void product(int m)
{
while(m!=0)
{
int a=m%10;
m=m/10;
prod=prod*a;
}
if(String.valueOf(prod).length()>1){
product(prod)
}
System.out.println(prod);
}
public static void main(String args[])
{
Scanner scn=new Scanner(System.in);
int x=scn.nextInt();
SmallestNum sn=new SmallestNum();
sn.product(x);
}
}

make member function product return to an int. then instead of sn.product(x);
int p = sn.product(x);
while (p > 9)
{
p = sn.product(t);
}

Related

Why my calculations are wrong? Java reverse int problem

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

While loop in Java :: keep dividing while contion is not met

I have a basic code:
public class experiment {
public static void main(String[] args) {
System.out.println(experiment(80));
}
public static int experiment (int number) {
while (number > 10) {
number = number / 2;
return number;
} return -1;
}
}
It returns me 40.
So it means is not looping on the variable number.
I would like it to keep looping on number (80, 40, 20, 10), till it return 10.
Is there a way to do it without using the for loop?
Move the return out of the loop:
public static int experiment (int number) {
while (number > 10) {
number = number / 2;
}
return number;
}
If you need the -1 for a special case, you should check it before entering the loop:
public static int experiment (int number) {
if (number < 0) { // or some condition
return -1;
}
while (number > 10) {
number = number / 2;
}
return number;
}
BTW, start using a debugger, you can step through this kind of code and find the problem easily.
What wrong is that you put return number inside the while loop it will end the iteration and return the value of 40. So you have to,
public static int experiment (int number) {
while (number > 10) {
number = number / 2;
}
return number;
}
If you want all the numbers the loop has passed to print;
public static void experiment (int number) {
while (number > 10) {
number = number / 2;
System.out.println(number);
}
}
using recursion:
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(test.toTen(80));
}
public static int toTen(int k) {
if (k==10) {
return k;
}
else {
return toTen(k/2);
}
}
}
or simply edit the loop like so
while (k > 10) {
k = k / 2;
}
return k;

Why am I getting a Time limit Exceeding? How can I improve the code?

the goal is to find the least number that is greater than n and the digit sum of that number canbe fully divided by 11. and after I run it, it return nothing.
public class M1
{
public static int nextCRC(int n)
{
int crc;
for (crc=n+1;crc!=0;crc++)
{
int sum=0;
for (crc =n+1 ; crc!=0; crc = crc / 10)
{
int digit = crc % 10;
sum += digit;
if ( sum %11 == 0)
{
break;
}
}
}
return crc;
}
public static void main(String[] args)
{
M1 Model=new M1();
Model.nextCRC(20);
System.out.println(Model.nextCRC(20));
}
}
Here is my solution:
import java.util.stream.LongStream;
/*
the goal is to find the least number that is greater than n and the digit sum of that number can be fully divided by 11.
*/
public class M1 {
private static long nextCRC(int n) {
return LongStream.iterate(n + 1, l -> ++l)
.filter(l -> sumOfBase10Digits(l) % 11 == 0)
.findFirst().getAsLong();
}
private static long sumOfBase10Digits(final long num) {
if (num == 0) {
return 0;
} else {
return num % 10 + sumOfBase10Digits(num / 10);
}
}
public static void main(String... args) {
System.out.println(nextCRC(20));
System.out.println(nextCRC(200));
System.out.println(nextCRC(98765));
System.out.println(nextCRC(92));
}
}
Here you go:
import java.math.*;
public class M1
{
public static int nextVal(int n)
{
int sum = 0;
int temp = n;
while(n>9){
sum = sum + n%10;
n = n/10;
}
sum = sum+n;
if((sum%11) == 0){
return temp;
}
return nextCRC(temp+1);
}
public static int nextCRC(int n) {
return nextVal(n+1);
}
public static void main(String[] args)
{
M1 Model=new M1();
Model.nextCRC(20);
System.out.println(Model.nextCRC(40));
}
}

Recursion - How can print each digit separately, rather than the sum of the number

input:
123
output:
6 >>> (It is the sum of all digits)
I want the output will:
321
That means each digit separately
What is wrong in the code?
The code:
public class t4 {
public static void main(String[] args) {
System.out.println(ReverseNum(123));
}
public static int ReverseNum(int num) {
int dig = 0;
if (num == 0)
return dig;
dig = dig * 10 + num % 10;
return ReverseNum(num / 10) + dig;
}
}
thank's
Try this.
public static void reverseMethod(int number) {
if (number < 10) {
System.out.println(number);
return;
}
else {
System.out.print(number % 10);
reverseMethod(number/10);
}
}
You can try:
public class t4 {
public static void main(String[] args) {
System.out.println(ReverseNum(123));
}
public static String ReverseNum(int num) {
if (num == 0)
return "";
return "" + num % 10 + ReverseNum(num / 10);
}
}
Find the largest power of ten smaller than the number first and use it to for reversing the number. This allows you to "move the digits to the right places":
public static int findPow10(int num) {
if (num < 10) {
return 1;
} else {
return 10 * findPow10(num / 10);
}
}
private static int reverseHelper(int num, int factor) {
if (num == 0) {
return 0;
} else {
return factor * (num % 10) + reverseHelper(num / 10, factor / 10);
}
}
public static int reverse(int num) {
return reverseHelper(num, findPow10(num));
}
public static void main(String[] args) {
System.out.println(reverse(123));
}
Rather than printing the values, I'm trying to return the number. This is what I could come up with so far. I think someone else might be able to do a better job. It's not that elegant with the while loop inside.
public static int ReverseNum(int num) {
if (num < 10){
return num;
}
int val = 1; int n = num;
while(n > 10){
n = n/10;
val = val * 10;
}
return (num % 10)*val + ReverseNum((num - num % 10)/10);
}
class Solution
{
//A method for reverse
public static void reverseMethod(int number)
{
if (number < 10)
{
System.out.println(number);
}
else {
System.out.print(number % 10); // 123 % 10 = 3
//Method is calling itself: recursion
reverseMethod(number/10); //123/10 = 12 integer ignore decimal number
}
}
public static void main(String args[])
{
reverseMethod(123);
}
}

Prime Factorization Program in Java Using Loops

I have to write a program that takes a number from the user and then displays the prime factors of the number. This is the program I have so far:
public static void main(String[] args) {
int a = getInt("Give a number: ");
int i = 0;
System.out.println("Your prime factors are: " + primeFactorization(a, i));
}
public static int getInt(String prompt) {
int input;
System.out.print(prompt);
input = console.nextInt();
return input;
}
public static int primeFactorization(int a, int i) {
for (i = 2; i <= a ; i++) {
while (a % i == 0) {
a /= i;
}
}
return i;
}
}
I can't figure out how to get it to print out the list of numbers. Any help is appreciated.
You should return a List<Integer> not a single int, and there is no point in i being an argument. A correct method is
public static List<Integer> primeFactorization(int a) {
List<Integer> list = new ArrayList<Integer>();
for (int i = 2; i <= a ; i++) {
while (a % i == 0) {
list.add(i);
a /= i;
}
}
return list;
}
While #Paul Boddington's answer is better in most cases (i.e. if you are using the values afterwards), for a simple program like yours, you could add all of the factors to a string and return the string. For example:
public static String primeFactorization(int a) {
String factors = "";
for (int i = 2; i <= a ; i++) {
while (a % i == 0) {
factors += i + " ";
a /= i;
}
}
return factors;
}

Categories