How can I reorder numbers in a int number to get minimum value.
Ex:
I input a number: $71440 and I want my output is: $1447 (this is minimum value after reordering). I think I will spits the numbers in my input number first like this , after that I will reorder them. That is good algorithm?
Yes it is good if you
split by digit
sort digits
make number out of those digits
What you need is essentially a sorting of the digits of the number. So yes, your proposed method will work and it seems as a reasonable practice.
I think this does roughly what you want it to do. Assumes that the input is positive, I'm sure you can figure out how to modify it to work with negative numbers if you need that.
public static int leastValue(int input) {
String s = Integer.toString(input);
char[] c = s.toCharArray();
Arrays.sort(c);
s = new String(c);
return Integer.parseInt(s);
}
The basic idea is:
Turn value into a string
Put each character into an array
Sort the array of characters, in most character sets this will order the numbers from smallest to largest.
Turn it into a string again
Parse it into an int
For readability I think Diasiares answer is better. However a different approach would be something like this. It sorts a long with a "merge sort like" algorithm. To understand how it works please view the gif file from wikipedia
public static long sort(long num) {
long res;
if (num > 9) {
//split num into two parts(n1, n2)
int numberOfDigits = (int) Math.log10(num) + 1;
long n1 = num / (long) Math.pow(10, numberOfDigits / 2);
long n2 = num % (long) Math.pow(10, numberOfDigits / 2);
//sort each part
long s1 = sort(n1);
long s2 = sort(n2);
//merge them into one number
res = merge(s1, s2);
} else {
res = num;
}
return res;
}
/**
* merges two sorted long into on long e.g 149 and 345 will give 134459
*/
public static long merge(long num1, long num2) {
return (num1 == 0 || num2 == 0)
? num1 + num2
: num1 % 10 < num2 % 10
? num2 % 10 + merge(num1, num2 / 10) * 10
: num1 % 10 + merge(num1 / 10, num2) * 10;
}
Related
How would you add digits to the beginning of a number (left hand side) without using a string?
I know that if you try this:
(Some psuedo code)
Let's say I try to make number 534
int current = 5;
int num = 0;
num = (num*10) +current;
then
int current = 3;
int num = 5
num = (num*10) + current;
would make: 53
then
int current = 4;
int num = 53;
num = (num*10) + current;
would make 534
It would keep adding numbers to the right hand side of the number.
However, I am a bit confused on how you would do the opposite. How would you add numbers on the left, so instead of 534 it makes 435?
int num = 123;
int digits = 456;
int powerOfTen = (int) Math.pow(10, (int) (Math.log10(digits) + 1));
int finalNum = digits * powerOfTen + num;
System.out.println(finalNum); // Output: 456123
The number of digits in digits is calculated using Math.log10 and Math.pow, and then used to determine the appropriate power of 10 to multiply digits by. The result is then added to num to obtain the final number with the added digits.
Multiply the digit to add by increasing powers of 10 before summing with the current number.
int num = 0, pow = 1;
num += 5 * pow;
pow *= 10;
num += 3 * pow;
pow *= 10;
num += 4 * pow; // num = 435 at this point
pow *= 10;
// ...
An example without the use of libraries could be this:
First, get the number of digits. Then calculate the number you have to add to your initial number. The sum of these two numbers is the result you're after.
private int addNumberInFrontOf(int initialNumber, int initialNumberToAdd){
int numberOfDigits = getDigits(initialNumber);
int getActualNumberToAdd = getNumberToAdd(initialNumberToAdd, numberOfDigits);
return initialNumber + getActualNumberToAdd;
}
To calculate the number of digits, you can count the number of times you can divide the initial number by 10. Notice you need to use a do-while loop because otherwise the loop wouldn't be triggered if your initial number was 0.
private int getDigits(int number) {
int count = 0;
do {
number = number / 10;
count += 1;
} while (number != 0);
return count;
}
Calculate the number you need to add to your initial number by multiplying the initial number to add with the magnitude. The magnitude simply is 1 multiplied with 10 for every digit in the initial number.
private int getNumberToAdd(int number, int numberOfDigits) {
int magnitude = 1;
for (int i = 0; i < numberOfDigits; i++) {
magnitude *= 10;
}
return number * magnitude;
}
For example, addNumberInFrontOf(456, 123) would result in 123456. Of course, this method won't work when you use positive and negative numbers combined.
You can use String for example.
public static int addLeft(int cur, int num) {
return num == 0 ? cur : Integer.parseInt(cur + String.valueOf(num));
}
In case you want to avoid working with String, you can use recursion instead.
public static int addLeft(int cur, int num) {
return num == 0 ? cur : addLeft(cur, num / 10) * 10 + num % 10;
}
You can use some math, in python
import math
def addLeft(digit, num):
return digit * 10 ** int(math.log10(num) + 1) + num
Note that this might fail for very large numbers on account of precision issues
>>> addLeft(2, 100)
2100
>>> addLeft(3, 99)
399
>>> addLeft(6, 99999999999999)
699999999999999
>>> addLeft(5, 999999999999999)
50999999999999999 (oops)
I'd like to know how to remove numbers from an integer. For example, if I have the number 23875326, I want to remove the odd numbers, and get the result of 2826.
I've been trying to break each number to check if it's even or odd using a while loop, but I don't know how to merge the numbers into one integer. One important thing is, I'd like to do it without using strings, as it doesn't teach me anything new that way.
I actually think that dealing with a string of numbers is preferable, not only from a code readability point of view, but also possibly from a performance view. That being said, if we absolutely cannot use strings here, then it is still possible to work directly with the integer input.
We can examine each tens digit of the input number using num % 10. Should that digit be even, we can add it to the output number, otherwise do not add it. Note that at each iteration we need to scale the digit by 10 to the correct exponent.
Here is a working code snippet:
int length = (int) (Math.log10(num) + 1); // finds the number of digits
int output = 0;
int counter = 0;
for (int i=0; i < length; ++i) {
if ((num % 10) % 2 == 0) {
output += (num % 10) * Math.pow(10, counter);
++counter;
}
num = num / 10;
}
System.out.println(output);
2826
Demo
I used #Tim Biegeleisen code and changed it a bit, removed some code and changed the for loop to while loop:
int output = 0;
int counter = 0;
System.out.println("Enter a number");
int num = s.nextInt();
while (num != 0) {
if ((num % 10) % 2 == 0) {
output += (num % 10) * Math.pow(10, counter);
++counter;
}
num = num / 10;
}
System.out.println(output);`
Say I have this integer in java, 987654321. I want to be able to remove, say the third and fourth digits, so I can get 9876521 in java.
I know I can do this by converting to a string, then taking a substring, but is there a way to do this without converting to a string?
% and / are your friends here! Using modulus and division we can get pieces of the number that we want.
We use modulus to eliminate the most significant digits, and division to eliminate the least significant digits. We can use division because the remainder gets truncated.
Then we put the two pieces we got from these two operations together. However, we need to shift the digits we got from the division to have room for the least significant digits.
Take 987654321 / 10000, this will give you 98765 (let's call this x)
Take 987654321 % 100, this will give you 21 (let's call this y)
x * 100 + y = 9876521.
More generally, if you want to remove a to bth digits from the number n (where a < b),
n % 10^(a-1) + ((n / 10^(b)) * 10^(a-1))
This will remove only one digit:
public static int RemoveNthPosition(int input, int position) {
int leftDivider = (int) Math.pow(10.0, position);
int rightDivider = (int) Math.pow(10.0, position - 1);
int leftSide = input / leftDivider;
int rightSide = input % rightDivider;
return leftSide * rightDivider + rightSide;
}
To remove multiple at the same time:
public static int RemoveMultiplePositions(int input, int[] positions) {
Arrays.sort(positions);
int result = input;
for (int count = 0; count < positions.length; count++) {
result = RemoveNthPosition(result, positions[count] - count);
}
return result;
}
In your case, it would be:
System.out.println(RemoveMultiplePositions(987654321, new int[] { 3, 4 }));
1. long number = 564;
2. String str = number+"";
3. char[] num = str.toCharArray();
4. number = number - num[0];
/* The value of number is 511 */
I am trying to subtract the first digit of the number from the number using this piece of code.
During debugging, i found out that the value of num[0] was 53. Can anyone explain what am i missing here.
I would suggest you to change your fourth line to this:
number = number - Long.parseLong(Character.toString(num[0]));
Basically, what is happening here is that I first convert the char (num[0]) to a string, then parsed the string to a long.
ALternatively, you don't even need to convert the string to a char array! Use charAt() to get the char:
number = number - Long.parseLong(Character.toString(str.charAt(0)));
When you are using the binary operator "-" the smaller datatype, in this case char, is promoted to long which returns the ASCII value of num[0] ('5') which is 53. To get the actual face value of num[0] convert it to String and parse it to Long as Sweeper has pointed out.
It just feels wrong to convert a number to a string, extract the first char, convert back to number and subtract. Why don't you extract the first digit while working with numbers directly. Something like this would do:
long number = 564;
int digits = 0;
assert (number > 0);
for (long num = number; num > 1; num = num / 10 ) {
digits += 1;
}
int firstDigit = (int) (number / Math.pow(10, digits -1));
number = number - firstDigit;
System.out.println(number);
If you want to get all digits:
long number = 564;
int digits = 0;
assert (number > 0);
for (long num = number; num > 1; num = num / 10 ) {
digits += 1;
}
for (int digit = digits - 1; digit >= 0; digit--) {
int currentDigit = (int) (number / Math.pow(10, digit)) % 10;
System.out.println(currentDigit);
}
I am trying to implementing Karatsuba's algorithm from wikipedia and I cannot continue to code since I do not know to how to split an integer into lower-half and upper-half. For example, if we have an integer 223, then it should be split into two integer 22 and 3.
How I might do this?
so it has to be something like
num1 = 223;
some magical stuff happening here!
low1 = 22;
low2 = 3;
Thank you very much I really appreciate your help!
low1 = num1 / 10;
low2 = num1 % 10;
This is the gist of what you're trying to accomplish. I'm not familiar with the algorithm and what exactly you're trying to do, so extra logic will almost certainly be required, but this is a good starting point.
You can use the modulus (%) operator to extract digits from a number. For example
12345 % 10 = 5
12345 % 100 = 45
12345 % 1000 = 345
And so on. Hope this helps.
you can use the modulus (%) operator to remove out the last number of an integer
int num1 = 223;
int num2 = num1%10;
num2 = 3 in this case
I would suggest this algorithm to split an integer :
int i = 233678546; /* The integer you would like to split */
int digitNumber = String.valueOf(i).length(); /* use java.math.Math.log10 if you need a more mathematical approach */
double val = Math.pow(10.0, (double)(digitNumber / 2));
int div = new Double(val).intValue();
int left = i / div;
int right = i % div;
StringBuilder sb = new StringBuilder();
sb.append("Value : ");
sb.append(i);
sb.append('\n');
sb.append("Left : ");
sb.append(left);
sb.append('\n');
sb.append("Right : ");
sb.append(right);
sb.append('\n');
System.out.println(sb.toString());