I don't understand the % comment.length bit of the following code:
comment.charAt(i % comment.length())
Does the part between the brackets convert to an integer with the value that represents i in relation to the comment length?
For instance, if:
comment = "test"
i = 2
what would comment.charAt(i % comment.length()) be?
% is the modulo operator, thus for your example i % comment.length() would resolve to 2 % 4 = 2. This would return the third character (at index 2).
The modulo operation seems to be a safeguard for cases where i >= comment.length().
Consider the following case: i = 11 and comment = "test".
If you just use comment.chatAt(i) you'd get an exception since there are only 4 characters. The modulo operation would wrap that around and result in 11 % 4 = 3 and return the fourth character (index 3) in that case.
% is the modulo operator: it gives you the remainder of an integer division
10 % 3 = 1
as 10 / 3 = 3 with a remainder of 1
Your statement just ensures that the function argument will be less then the string length.
But I would rather check this in another way. It is pretty counterintuitive to ask for character at position 11 in a string long 10 characters and get the character at position 1 instead of a warning or error message.
Related
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.
Would this test work?:
if (testInt/2).ofType(Integer){
//to-do if even
}
I assume it would iff the compiler resolves testInt/2 before ofType(); is this the case??
Best way to do it is always use the modulus operator.
if (testInt % 2 == 0)
{
//Do stuff
}
//3 % 2 = 1 , therefore odd
//4 % 2 = 0 , therefore even
Modulus is just getting the remainder from division.
Using the modulus operator works, but there's a better way to check. The least significant bit is 0 for all even numbers, and 1 for odds. Performing a bitwise AND operation with 1, will clear all but the LSB. Check the bit to determine the integer's parity. Less memory is used to clear bits than to compute a remainder.
if ((testInt & 1) == 0) //Even Number
if ((testInt & 1) == 1) //Odd Number
/*
4 & 1 = 0
5 & 1 = 1
1342424 & 1 = 0
5987833 & 1 = 1
*/
Would this test work?
No. The expression performs integer division (because both operands are integers), and the result of the expression always has type int. So for example
1 / 2 => 0 // not 0.5
2 / 2 => 1
-3 / 2 => -2 // not -1.5 or -1 ...
// integer division rounds towards minus infinity
I assume it would iff the compiler resolves testInt/2 before ofType(); is this the case??
The compiler resolves the static type of testInt/2 at compile time while the instanceof test is performed at runtime.
However, your assumption is incorrect because it is based on an incorrect understanding expressions and typing.
The compile time type of an expression does not depend on the values of the operands. It only depends on the operands' compile-time types.
For primitive types, there is no polymorphism, so the runtime type and the compile time type are the same.
As #Cameron C states, the correct way to do the test is to use the modulus operator %.
#styro's approach works, but:
is it less readable (IMO)
it is possibly slower
if it is faster, it probably doesn't matter.
Try this code...
public static boolean isEven (int testInt) {
int i=0;
while (i <= testInt) {
if (i==testInt) return true;
i+=2;
}
return false;
}
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.
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
I need to split the bits of a number say 9(1001) in two equal sized parts 10 and 01 in this case.
My first idea was to just shift it but for the right number I dont get the expected result ,I suspect this is due to the sign(no unsigned in java :( ).
My current code is the following:
long num=9;
System.out.println(Long.toBinaryString(num));
long num1=num>>2;
System.out.println(Long.toBinaryString(num1));
long num2=num<<2;
System.out.println(Long.toBinaryString(num2));
Output:
1001
10
100100
Any workaround?
To get the lower part, you need to use bitwise AND... so if you shift right by 2 bits to get the higher part, you need to AND with binary number 11 (two bits as 1) to get the lower part. Here's code which should do it for any shift:
long num = 9;
int shift = 2
System.out.println(Long.toBinaryString(num));
long num1 = num >> shift;
System.out.println(Long.toBinaryString(num1));
long num2 = num & ( (1<<shift) - 1);
System.out.println(Long.toBinaryString(num2));
Explanation of calculating num2, for shift 2, 0b means binary literal, in pseudocode:
( (1<<shift) - 1) == ( (1<<2) - 1) == ( 0b100 - 1) == 0b11 == two bits set
From that it should be clear how it will work for any shift value.
You could shift num1 back 2 and the subtract it from num. This will give you num2.