Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
In Java, the following code:
long x = 123;
String s = "abc" + x;
takes a significantly more runtime than:
long x = 123;
String s = "abc" + String.valueOf(x);
I got to know this through leetcode. I was trying to solve the following problem: https://leetcode.com/problems/fraction-to-recurring-decimal/
Here is the exact code for my solution:
public String fractionToDecimal(int numerator, int denominator) {
long n = numerator, d = denominator;
boolean isNegative = (n * d < 0);
if(n < 0) n = -n;
if(d < 0) d = -d;
long q = n / d;
long r = n % d;
if(r == 0) return (isNegative ? "-" : "") + q;
StringBuilder sb = new StringBuilder();
if(isNegative) sb.append('-');
sb.append(q).append('.');
Map<Long, Integer> found = new HashMap<>();
int index = sb.length();
while(r > 0 && !found.containsKey(r)){
found.put(r, index++);
n = r * 10;
q = n / d;
r = n % d;
sb.append(q);
}
if(r > 0) {
sb.insert(found.get(r), "(");
sb.append(')');
}
return sb.toString();
}
When I click on Submit it takes as long as 7 milliseconds to complete.
But if I literally just change line no. 8 from + q to + String.valueOf(q) the runtime plummets down to just 1 millisecond. Please feel free to copy paste the code on leetcode to try it out there and see this change in runtime for yourself, if necessary.
This is highly confusing to me. Why is this happening? As per my understanding, in both the cases, compiler first converts the long to a String, and then concatenates those two Strings together, right? So, under the hood, isn't concatenating a String and a long exactly the same as concatenating two Strings together? Then why does one take more time to run than the other? Any insight would be highly appreciated. TIA.
Note: this answer was written before the question was changed. It used to include the expressions shown below.
"abc" + 123 is a constant expression - the concatenation is done at compile-time so "abc123" ends up in the constant pool.
"abc" + String.valueOf(123) is not a constant expression. The concatenation happens at execution time, which is obviously rather more expensive than just using the compile-time concatenation result.
So I'd expect the result to be the opposite of what you've actually reported in the question.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Java Code Example: i am facing issue when i insert 010 it shows only 1 instead of whole number and when i insert 200 it gave me reverse number only 2 while it should show me exact 002 how can i get exact number in reverse:
class Reverse{
public static void main(String args[]){
int remander,sum=0;
int number=454;
while(n>0) // loop here
{
remander=n%10; // Getting remainder
sum=(sum*10)+remander;
number=number/10;
}
System.out.println("Reverse"+sum);
}
}
It is clear that you are new to Java, and new to programming. Welcome to StackOverflow. I'm going to add some extra advice that I don't normally offer, to help you get better faster.
Don't reuse a variable for more than one thing. Use it for only one thing. That means that if a variable holds you input, don't overwrite it with intermediate values. Variables are (relatively) cheap, create another. You can practice this by marking your variables final which will prevent you from changing their values after assigned.
Use meaningful variable names. "r" is not a meaningful name. "remainder" is a meaningful name. This helps others immediately, and will help you later, when the program isn't fresh on your mind and you don't remember what "r" means.
Once you master not reusing variables, you will have a lot of variables. Look for variables that are "set once and read once" and try to rearrange your code to remove them completely. It will take some time to understand what I mean, but if you have heard of "refactoring" the idea is to remove the variable name because it isn't used twice (so it probably isn't a key part of your problem.
Now, applying these rules
final int number = 454;
// get the number digits, smallest to largest
int remainder = number;
int accumulator = 0;
while (remainder > 0) {
final int digit = remainder % 10;
accumulator = accumulator * 10 + digit;
remainder = remainder / 10;
}
final int reversed = accumulator;
note that digit is never used twice
final int number = 454;
// get the number digits, smallest to largest
int remainder = number;
int accumulator = 0;
while (remainder > 0) {
accumulator = accumulator * 10 + remainder % 10;
remainder = remainder / 10;
}
final int reversed = accumulator;
Note that all that "logic" could have a really good name put to it, so we'll create a "method"
public int reverse(int value) {
int remainder = value;
int accumulator = 0;
while (remainder > 0) {
accumulator = accumulator * 10 + remainder % 10;
remainder = remainder / 10;
}
return accumulator;
}
which cleans up the other code to
final int number = 454;
final int reversed = reverse(number);
or maybe even
final int reversed = reverse(454);
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have a question regarding this problem and my solution. Given three sequences a,b,c - I used the logic of finding the longest common sub-sequence value of each pair (a,b), (b,c) and (c,a). Then finding the minimum of the three. Which should give us the longest common sub-sequence value.
I was wondering why my solution would not be robust? The code I used is below (in JAVA).
DRIVER CODE:
int result1 = DynamicProgramming.longestCommonSequence(a, b);
int result2 = DynamicProgramming.longestCommonSequence(b, c);
int result3 = DynamicProgramming.longestCommonSequence(c, a);
int temp = Math.min(result1, result2);
System.out.println(Math.min(result3, temp));
PROGRAM LOGIC:
public static int longestCommonSequence(int[] a, int[] b) {
int[][] aS = new int[a.length + 1][b.length + 1];
int tempAS;
for (int i = 0; i < aS.length; i++)
for (int j = 0; j < aS[0].length; j++) {
if (i == 0) {
aS[i][j] = j;
} else if (j == 0) {
aS[i][j] = i;
} else {
int ins = aS[i][j - 1] + 1;
int del = aS[i - 1][j] + 1;
int mat = aS[i - 1][j - 1];
tempAS = Math.min(ins, del);
if (a[i - 1] == b[j - 1])
aS[i][j] = Math.min(mat, tempAS);
else
aS[i][j] = tempAS;
}
}
return (a.length + b.length - aS[a.length][b.length]) / 2;
}
The program works in all test cases I have tried. But when I submitted it to an online automatic tester it failed on the last test case(edx course). I am unable to think of a situation where the solution would fail. Any help would be greatly appreciated.
We can assume that all input values are valid integers and the arrays a,b,c are not null.
PS: I have already found and alternate solution that passes all the tests. But I was curious to know the flaw in my logic. Thanks.
if string a was aaaaaaaabbbbbbb
and string b was bbbbbbbbccccccc
and string c was ccccccccaaaaaaa
then (a,b) have a common subsequence of length 7
and (b,c) have a common subsequence of length 7
and (c,a) have a common subsequence of length 7
but is there a subsequence that is common to all 3?
(Answer: no... and so the idea of just taking the min of the 3 pairwise comparisons is flawed)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am trying to solve uVa's 369(Combinations) problem using Modular Arthimetic and Binary Exponentiation instead of just using BigInteger class in java. I am able to pass the last two base test cases but not the first test case. Can anybody explain where my code is wrong ?
public class Main {
static long M = 1000000007;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while(true){
String s = br.readLine();
s = s.trim();
s = s.replaceAll("\\s{2,}", " ");
String[] str = s.split(" ");
long n = Long.parseLong(str[0]);
long m = Long.parseLong(str[1]);
if(n == 0 && m == 0) break;
long a = fact(n); long b = fact((n-m) % M); long c = fact(m);
long d = (b*c) % M;
long ans = divide(a,d);
System.out.println(n + " things taken " + m + " at a time is " + ans + " exactly");
}
}
public static long fact(long N){
long ans = 1;
for(int i=1; i<=N; ++i)
ans = (ans * i) % M;
return ans;
}
public static long divide(long a, long b){
return a * pow(b,M-2) % M;
}
public static long pow(long a, long b){
long res = 1;
while(b > 0){
if(b % 2 == 1) res = (res*a) % M;
a = (a*a) % M;
b /=2;
}
return res;
}
}
M is too small. For example for the input 100 6, the correct result is 1192052400, but since your code works modulo 1000000007 the result will be 1192052400 mod 1000000007 = 192052393, which is much smaller (not just 7 smaller).
Using M = 0x7fffffff (also a prime) may work.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
the string is 1a2a(3a4) then I am able to extract (3a4) & calculate it, let 'x' be the answer then substitute to main 1a2ax & calculate as normal (which is easy, I have done. ( a - add, s - sub, m - mul, d - div)
for above equation, I have done like this (works only if I have one set of brackets)
public class task2 {
private static double parseString(String str) {
// declaring the operators' counters
int a = 1;
int s = 1;
int m = 1;
int d = 1;
// splitting the string up into operands and operators
double[] operands = Arrays.stream(str.split("[asmd]")).mapToDouble(Double::parseDouble).toArray();
String[] operators = str.split("\\d+");
// the rest is pretty much self-explanatory
double total = operands[0];
for (int i = 1 ; i < operators.length ; i++) { // note that i starts at 1 because the first item in operators
switch (operators[i]) { // array is an empty string
case "a":
total = total * a + operands[i];
a++;
break;
case "s":
total = total * s - operands[i];
s++;
break;
case "d":
total = total * d / operands[i];
d++;
break;
case "m":
total = total * m * operands[i];
m++;
break;
}
}
return total;
}
public static void main(String[] args){
String x= "1a(2a6a16)a9s88s77m9d5";
System.out.print("Expression \""+x+"\" on solving gives answer as ");
//To extract String with Bracket
Matcher m = Pattern.compile("\\((.*?)\\)").matcher(x);
String y = null;
while(m.find()) {
y = m.group(1);
}
String z = Double.toString(task2.parseString(y));
int p = (int)Double.parseDouble(z);
String q = Integer.toString(p);
x = x.replaceAll("\\p{P}","");
x = x.replace(y,q);
// To call method to find value
System.out.println(task2.parseString(x));
}
}
But prob comes when an equation is
((1a3a(9s9s(10d200))s(10m100a(192s187))a10)d2d8)
, when I have to apply the recursive extract of innermost parenthesis until no more parenthesis, which I am struggling with.
firstly (10d200) extracted and calculated, let the answer be "P", the equation becomes ((1a3a(9s9sP)s(10m100a(192s187))a10)d2d8)
secondly (9s9sp) extracted and calculated, let answer be "Q", equation becomes ((1a3aQs(10m100a(192s187))a10)d2d8)
thirdly (192s187) extracted and calculated, let answer be "R", equation becomes ((1a3aQs(10m100aR)a10)d2d8)
forthly (10m100aR) extracted and calculated, let answer be "S", equation becomes ((1a3aQsSa10)d2d8)
fifthly (Td2d8) expression calculated.
Plz, Help me out here. Thanks in advance.
Pseudocode:
while (there are parentheses left) {
find first closing parenthesis;
walk left and find nearest opening parenthesis;
evaluate expression inbetween;
replace expression with result and remove parentheses;
}
evaluate expression;
Edit: Just for completeness, this can be written in a compact way using peg.js: https://jsfiddle.net/mxLq9drm/2
The simplest way would be to always parse the content of the first pair of brackets:
stack s
for i = 0; i < len(text); i++ do
if text[i] is openingbracket
s.push(i)
if next character is closing bracket
pos = s.pop()
res = parse(text, pos + 1, i - 1)
text.replace(pos, i, res) //update the string to parse
i = pos + len(res) //set i to the end of the newly inserted string
The basic idea is to store the indices of all opening-brackets in a stack. If a closing-bracket is encountered, take the string between the last opening-bracket (head of the stack) and the current position, evaluate the expression and replace it in the string. Afterwards update the current position in the string and proceed to parse.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
Just started picking up java and tried to write a simple piece of code to display an approximation of Pi based on the Gauss-Legendre algorithm; the result I get in the command line from the code below is -33.343229... which seems very odd to me. I am aware that my code is not complete as I do not have a restriction on the number of digits after the decimal point, which I was going to try and get from using BigDecimal. I don't quite understand what I am supposed to do with it though after reading the documentation!
Does anyone have any idea if there are any current mistakes I can fix and also how to implement a restriction on the number of digits after the decimal point? Thank you!
class calculatePi {
public static void main(String[] args) {
calculatePi x = new calculatePi();
double y = x.approxPi(3); //3 iterations
System.out.print(y);
}
double approxPi(int i) {
double a = 1; //The initial conditions for the iteration
double b = 1 / Math.sqrt(2);
double t = 1/4;
double p = 1;
double a1 = 0; //The internal n+1 terms for the iteration
double b1 = 0;
double t1 = 0;
double p1 = 0;
while (i > 0) {
a1 = (a + b) / 2;
b1 = Math.sqrt(a*b);
t1 = t - p*(a - a1)*(a - a1);
p1 = 2*p;
a = a1;
b = b1;
t = t1;
p = p1;
i = i - 1;
}
double applepie = ((a + b)*(a + b))/(4*t);
return applepie;
}
}
double t = 1/4; does an integer division for 1/4, which results in 0. Try 1/4.0.