how a splitting number to a separate digits algorithm works - java

i'm getting back to software development and i was playing around with algorithms in java,and today i'm doing the algorithm the splits a number to a separate digits, I've found it here i wrote it in java ..it works but honestly i don't how ?? there is the code just i didn't understand a part of it :
public static void main(String[] args) {
Integer test = 0, i, N;
ArrayList array_one= new ArrayList<Integer>();
Scanner sc = new Scanner(System.in);
System.out.print("Write An Integer :");
test = sc.nextInt();
while (test > 0){
int mod = test % 10; // <= DON'T UNDERSTAND THE WORK OF THAT PART
// (i know it's the modulo of the entered value)
test = test / 10;
array_one.add(mod);
}
System.out.print(array_one);
}
i know it's a newbie question i'm just passionate about software engineering and algorithms just want to know how it exactly works and thks in advance.

test % 10; gives you the last (least significant) digit of the number, which is the remainder when dividing the number by 10.
test = test / 10 reduces the number by one digit (123456 becomes 12345), making the former 2nd least significant digit the new least significant digit. Therefore, in the next iteration, test % 10; would return the 2nd digit.
And so on...

test % 10; --> Always gives you the last digit.
test / 10; --> divides the existing number by 10.
while loop --> executes until test > 0
So, if your number is 234,
234%10 would be 4
234/10 would be 23.4 which will be converted to 23.
Apply 23 % 10 and 23/10 and so on..

By using %10 you'll get only the last digit.
/10 will give what is before your last digit.
And so you can construct your array.
124%10 --> 4
124/10 --> 12 % 10 --> 2
12 / 10 --> 1

The logic used here is to separate the units place first by dividing the number by 10 and getting the reminder value.
e.g x=153
"% " is the modulus operator that gives the remainder of the division
"/" is the division operator that gives only the quotient
then 153%10= 3 //this is the remainder that separates the first digit.
The number is then divided by 10 so as to get the quotient
i.e 153/10 =15 // Only the quotient
Progressing with the loop, now 15 is taken as the new original number and is again divided by 10 to get the remainder and hence the next digit.
i.e 15%10 =5 //next digit
15/10=1;
1%10=1 //digit
1/10=0 //The loop ends here

You can understand it by an example
Your number to divide it's digits is 345
If you divide it by 10 your remaining and first digit is 5

Related

How can I add a placeholder to a random Int then pull a single digit from that Int in Java?

I am new to Java and programming all together.. I am trying to make a program that ciphers a number for the user. The user inputs 5 digits separately so I add them together to get a total. I need to pull the first digit and second digit of the total and enter it into (firstDigit+key)%10 and (secondDigit+key)%10. Then need to combine the answer to each equation together.
My total needs to be two digits, so even if the user enters all 1's which would total to be 5, I need it to be displayed and seen as 05 so that both equations have a digit to use. It needs to be two digits. I cant seem to figure how to enter a place holder. I was thinking about trying to use:
if (total < 10)
but then what?
Secondly, the method I used below seems like a terrible way to pull a single digit from a number. I think I changed the int total into a string so I can use .substring to pull the digits, then converted back to an int. Surprisingly it works. Is there a better way to do this knowing that the number is random?
String totalString = Integer.toString(total);
String stringDigit1 = totalString.substring(0,1);
String stringDigit2 = totalString.substring(1,2);
int firstDigitInt1 = Integer.parseInt(stringDigit1);
int firstDigitInt2 = Integer.parseInt(stringDigit2);
int encodedDigit1 = (firstDigitInt1+key)%10;
int encodedDigit2 = (firstDigitInt2+key)%10;
System.out.println("Your encoded Number is: " + encodedDigit1 + encodedDigit2);
Your method for obtaining the individual digits is good, and if you want to maintain it I believe your intuition is correct, it should suffice to say:
if (total < 10) {
firstDigitInt1 = 0
}
This will work out with your following math.
Your method with substrings is far from terrible, but in case you wanted something more sleek you can instead say:
int Digit1 = total / 10;
int Digit2 = total % 10;
Here, you can take advantage of integer truncation (where an integer won't remember decimal places) to get the first digit, which also solves the first problem: 5 / 10 = 0 (in terms of ints). For the second digit, it suffices to say modulo 10, as it is the remainder once the total is divided by 10.

find a number in another number without using Array

Recently i attended an interview where i was asked to write a function to find a term in a number and the number of times it occurs.
Lets say term = 51, number = 164518351, so 51 does exits in number and it occurs for 2 times, so return 2.
My Solution - Convert the number and term into string and , replace term string with "A" in the number string and then finally count the number of "A" in the number string. He asked me to solve without using strings, so i gave an array approach.
But he said that i cannot use arrays as well. so i want to know if there are other ways to do this ? I don't want the exact code or algo i just want to know various approaches we can take to solve this problem in minimum time complexity.
you can try something like this
int term_count = 0;
while(number > 0){
if(number % 100 == term)
term_count++;
number = number/10
}
This will check if the last two digits of the number is equal to the term, and continue doing so ignoring every unit digits of the number.
something like this
164518351 % 100 == 51
16451835 % 100 == 51
1645183 % 100 == 51
164518 % 100 == 51
....
of course, here i know that the term is two digits and so i mod by 100. if you don't know that, you can find the number of digits in the term and then mod number by
10^(num_of_digits_in_term)
you can find the number of digits like this
int tempTerm = term, termDigitCount = 0;
while(tempTerm > 0){
termDigitCount++;
tempTerm /= 10;
}
// 51 > 0 -> termDigitCount = 1
// 1 > 0 -> termDigitCount = 2
// 0 > 0 -> exit while loop
and in the end if the term_count is 0, then there is no occurrence of the term in the number
Hope this helps.
P.S - the solution may not be syntactically correct since OP does not want an exact answer. just the logic.

How to convert large integer number to binary?

Sorry for a possible duplicate post, I saw many similar topics here but none was exactly I needed. Before actually posting a question I want to explicitly state that this question is NOT A HOMEWORK.
So the question is: how to convert a large integer number into binary representation? The integer number is large enough to fit in primitive type (Java long cannot be used). An input might be represented as a string format or as an array of digits. Disclaimer, This is not going to be a solution of production level, so I don't want to use BigInteger class. Instead, I want to implement an algorithm.
So far I ended up with the following approach:
Input and output values represented as strings. If the last digit of input is even, I prepend the output with "0", otherwise - with "1". After that, I replace input with input divided by 2. I use another method - divideByTwo for an arithmetical division. This process runs in a loop until input becomes "0" or "1". Finally, I prepend input to the output. Here's the code:
Helper Method
/**
* #param s input integer value in string representation
* #return the input divided by 2 in string representation
**/
static String divideByTwo(String s)
{
String result = "";
int dividend = 0;
int quotent = 0;
boolean dividendIsZero = false;
while (s.length() > 0)
{
int i = 1;
dividend = Character.getNumericValue(s.charAt(0));
while (dividend < 2 && i < s.length())
{
if (dividendIsZero) {result += "0";}
dividend = Integer.parseInt(s.substring(0, ++i));
}
quotent = dividend / 2;
dividend -= quotent * 2;
dividendIsZero = (dividend == 0);
result += Integer.toString(quotent);
s = s.substring(i);
if (!dividendIsZero && s.length() != 0)
{
s = Integer.toString(dividend) + s;
}
}
return result;
}
Main Method
/**
* #param s the integer in string representation
* #return the binary integer in string representation
**/
static String integerToBinary(String s)
{
if (!s.matches("[0-9]+"))
{
throw new IllegalArgumentException(s + " cannot be converted to integer");
}
String result = "";
while (!s.equals("0") && !s.equals("1"))
{
int lastDigit = Character.getNumericValue(s.charAt(s.length()-1));
result = lastDigit % 2 + result; //if last digit is even prepend 0, otherwise 1
s = divideByTwo(s);
}
return (s + result).replaceAll("^0*", "");
}
As you can see, the runtime is O(n^2). O(n) for integerToBinary method and O(n) for divideByTwo that runs inside the loop. Is there a way to achieve a better runtime? Thanks in advance!
Try this:
new BigDecimal("12345678901234567890123456789012345678901234567890").toString(2);
Edit:
For making a big-number class, you may want to have a look at my post about this a week ago. Ah, the question was by you, never mind.
The conversion between different number systems in principle is a repeated "division, remainder, multiply, add" operation. Let's look at an example:
We want to convert 123 from decimal to a base 3 number. What do we do?
Take the remainder modulo 3 - prepend this digit to the result.
Divide by 3.
If the number is bigger than 0, continue with this number at step 1
So it looks like this:
123 % 3 == 0. ==> The last digit is 0.
123 / 3 == 41.
41 % 3 == 2 ==> The second last digit is 2.
41 / 3 == 13
13 % 3 == 1 ==> The third digit is 1.
13 / 3 == 4
4 % 3 == 1 ==> The fourth digit is 1 again.
4 / 3 == 1
1 % 3 == 1 ==> The fifth digit is 1.
So, we have 11120 as the result.
The problem is that for this you need to have already some kind of division by 3 in decimal format, which is usually not the case if you don't implement your number in a decimal-based format (like I did in the answer to your last question linked above).
But it works for converting from your internal number format to any external format.
So, let's look at how we would do the inverse calculation, from 11120 (base 3) to its decimal equivalent. (Base 3 is here the placeholder for an arbitrary radix, Base 10 the placeholder for your internal radix.) In principle, this number can be written as this:
1 * 3^4 + 1 * 3^3 + 1*3^2 + 2*3^1 + 0*3^0
A better way (faster to calculate) is this:
((((1 * 3) + 1 )*3 + 1 )*3 + 2)*3 + 0
1
3
4
12
13
39
41
123
123
(This is known as Horner scheme, normally used for calculating values of polynomials.)
You can implement this in the number scheme you are implementing, if you know how to represent the input radix (and the digits) in your target system.
(I just added such a calculation to my DecimalBigInt class, but you may want to do the calculations directly in your internal data structure instead of creating a new object (or even two) of your BigNumber class for every decimal digit to be input.)
Among the simple methods there are two possible approaches (all numbers that appear here decimal)
work in decimal and divide by 2 in each step as you outlined in the question
work in binary and multiply by 10 in each step for example 123 = ((1 * 10) + 2) * 10 + 3
If you are working on a binary computer the approach 2 may be easier.
See for example this post for a more in-depth discussion of the topic.
In wikipedia, it is said:
For very large numbers, these simple methods are inefficient because
they perform a large number of multiplications or divisions where one
operand is very large. A simple divide-and-conquer algorithm is more
effective asymptotically: given a binary number, it is divided by
10^k, where k is chosen so that the quotient roughly equals the
remainder; then each of these pieces is converted to decimal and the
two are concatenated. Given a decimal number, it can be split into two
pieces of about the same size, each of which is converted to binary,
whereupon the first converted piece is multiplied by 10^k and added to
the second converted piece, where k is the number of decimal digits in
the second, least-significant piece before conversion.
I have tried, this method is faster than conventional one for numbers larger than 10,000 digits.

From 5 dice rolls, generate a random number in the range [1 - 100]

I was going through some coding exercises, and had some trouble with this question:
From 5 dice (6-sided) rolls, generate a random number in the range [1 - 100].
I implemented the following method, but the returned number is not random (called the function 1,000,000 times and several numbers never show up in 1 - 100).
public static int generator() {
Random rand = new Random();
int dices = 0;
for(int i = 0; i < 5; i++) {
dices += rand.nextInt(6) + 1;
}
int originalStart = 5;
int originalEnd = 30;
int newStart = 1;
int newEnd = 100;
double scale = (double) (newEnd - newStart) / (originalEnd - originalStart);
return (int) (newStart + ((dices - originalStart) * scale));
}
Ok, so 5 dice rolls, each with 6 options. if they are un-ordered you have a range of 5-30 as mentioned above - never sufficient for 1-100.
You need to assume an order, this gives you a scale of 1,1,1,1,1 - 6,6,6,6,6 (base 6) assuming 1 --> 0 value, you have a 5 digit base 6 number generated. As we all know 6^5 = 7776 unique possibilities. ;)
For this I am going to give you a biased random solution.
int total = 0;
int[] diceRolls;
for (int roll : diceRolls) {
total = total*6 + roll - 1;
}
return total % 100 + 1;
thanks to JosEdu for clarifying bracket requirement
Also if you wanted to un-bias this, you could divide range by the maxval given in my description above, and subsequently multiply by your total (then add offset), but you would still need to determine what rounding rules you used.
Rolling a 6 sided die 5 times results in 6^5 = 7776 possible sequences, all equally probable. Ideally you'd want to partition those sequences into 100 groups of equal size and you'd have your [1 - 100] rng, but since 7776 isn't evenly divisible by 100 this isn't possible. The best you can do to minimize the bias is 76 groups mapped to by 78 sequences each and 24 groups mapped to by 77 sequences each. Encode the (ordered) dice rolls as a base 6 number n, and return 1 + (n % 100).
Not only is there no way to remove the bias with 5 dice rolls, there is no number of dice rolls that will remove the bias entirely. There is no value of k for which 6^k is evenly divisible by 100 (consider the prime factorizations). That doesn't mean there's no way to remove the bias, it just means you can't remove the bias using a procedure that is guaranteed to terminate after any specific number of dice rolls. But you could for example do 3 dice rolls producing 6^3 = 216 sequences encoded as the base 6 number n, and return 1 + (n % 100) if n < 200. The catch is that if n >= 200 you have to repeat the procedure, and keep repeating until you get n < 200. That way there's no bias but there's also no limit to how long you might be stuck in the loop. But since the probability of having to repeat is only 16/216 each time, from a practical standpoint it's not really much of a problem.
The problem is there aren't enough random values in 5-30 to map one to one to 1-100 interval. This means certain values are destined to never show up; the amount of these "lost" values depends on the size ratio of the two intervals.
You can leverage the power of your dice in a way more efficient way, however. Here's how I'd do it:
Approach 1
Use the result of the first dice to choose one subinterval from the
6 equal subintervals with size 16.5 (99/6).
Use the result of the second dice to choose one subinterval from the 6 equal sub-subintervals of the subinterval you chose in step one.
Use... I guess you know what follows next.
Approach 2
Construct your random number using digits in a base-6 system. I.E. The first dice will be the first digit of the base-6 number, the second dice - the second digit, etc.
Then convert to base-10, and divide by (46656/99). You should have your random number. You could in fact only use 3 dice, of course, the rest two are just redundant.

How can I round manually?

I'd like to round manually without the round()-Method.
So I can tell my program that's my number, on this point i want you to round.
Let me give you some examples:
Input number: 144
Input rounding: 2
Output rounded number: 140
Input number: 123456
Input rounding: 3
Output rounded number: 123500
And as a litte addon maybe to round behind the comma:
Input number: 123.456
Input rounding: -1
Output rounded number: 123.460
I don't know how to start programming that...
Has anyone a clue how I can get started with that problem?
Thanks for helping me :)
I'd like to learn better programming, so i don't want to use the round and make my own one, so i can understand it a better way :)
A simple way to do it is:
Divide the number by a power of ten
Round it by any desired method
Multiply the result by the same power of ten in step 1
Let me show you an example:
You want to round the number 1234.567 to two decimal positions (the desired result is 1234.57).
x = 1234.567;
p = 2;
x = x * pow(10, p); // x = 123456.7
x = floor(x + 0.5); // x = floor(123456.7 + 0.5) = floor(123457.2) = 123457
x = x / pow(10,p); // x = 1234.57
return x;
Of course you can compact all these steps in one. I made it step-by-step to show you how it works. In a compact java form it would be something like:
public double roundItTheHardWay(double x, int p) {
return ((double) Math.floor(x * pow(10,p) + 0.5)) / pow(10,p);
}
As for the integer positions, you can easily check that this also works (with p < 0).
Hope this helps
if you need some advice how to start,
step by step write down calculations what you need to do to get from 144,2 --> 140
replace your math with java commands, that should be easy, but if you have problem, just look here and here
public static int round (int input, int places) {
int factor = (int)java.lang.Math.pow(10, places);
return (input / factor) * factor;
}
Basically, what this does is dividing the input by your factor, then multiplying again. When dividing integers in languages like Java, the remainder of the division is dropped from the results.
edit: the code was faulty, fixed it. Also, the java.lang.Math.pow is so that you get 10 to the n-th power, where n is the value of places. In the OP's example, the number of places to consider is upped by one.
Re-edit: as pointed out in the comments, the above will give you the floor, that is, the result of rounding down. If you don't want to always round down, you must also keep the modulus in another variable. Like this:
int mod = input % factor;
If you want to always get the ceiling, that is, rounding up, check whether mod is zero. If it is, leave it at that. Otherwise, add factor to the result.
int ceil = input + (mod == 0 ? 0 : factor);
If you want to round to nearest, then get the floor if mod is smaller than factor / 2, or the ceiling otherwise.
Divide (positive)/Multiply (negative) by the "input rounding" times 10 - 1 (144 / (10 * (2 - 1)). This will give you the same in this instance. Get the remainder of the last digit (4). Determine if it is greater than or equal to 5 (less than). Make it equal to 0 or add 10, depending on the previous answer. Multiply/Divide it back by the "input rounding" times 10 - 1. This should give you your value.
If this is for homework. The purpose is to teach you to think for yourself. I may have given you the answer, but you still need to write the code by yourself.
Next time, you should write your own code and ask what is wrong
For integers, one way would be to use a combination of the mod operator, which is the percent symbol %, and the divide operator. In your first example, you would compute 144 % 10, resulting in 4. And compute 144 / 10, which gives 14 (as an integer). You can compare the result of the mod operation to half of the denominator, to find out if you should round the 14 up to 15 or not (in this case not), and then multiply back by the denominator to get your answer.
In psuedo code, assuming n is the number to round, p is the power of 10 representing the position of the significant digits:
denom = power(10, p)
remainder = n % denom
dividend = n / denom
if (remainder < denom/2)
return dividend * denom
else
return (dividend + 1) * denom

Categories

Resources