#include <stdio.h> #include <string.h> #define MAXSIZE 10011 int n, ans, k, coe, len, outcome, c[MAXSIZE]; char e[MAXSIZE], s[MAXSIZE]; void sort(int x) { int i, j, t; for(i = 1; i < x; i ++){ for(j = i+1; j > 1; j--){ if(c[j] < c[j-1]){ t = c[j-1]; c[j-1] = c[j]; c[j] = t; }else{ break; } } } } int calculate() { int i, j; k = outcome = 0; strcpy(s, e); len = strlen(s); if(s[0] != '-'){ for(i = len + 1; i > 0; i --){ s[i] = s[i-1]; } s[0] = '+'; len ++; } for(i = 0; i < len; i += 3){ if(s[i] == '+'){ coe = 1; }else{ coe = -1; } i ++; j = 0; while('0' <= s[i] && s[i] <= '9'){ j *= 10; j += s[i++] - '0'; } if(s[i] == '*'){ i ++; }else{ j = 1; } coe *= j; c[++k] = coe; outcome += (n-(s[i] == 'a')) * coe; } sort(k); for(i = 1; i <= k; i ++){ outcome += i * c[i]; } return outcome; } int main() { scanf("%d %s", &n, e); ans = calculate(); printf("%d\n", ans); return 0; }把这个转化成java代码
时间: 2024-02-10 08:33:40 浏览: 52
把C代码转换成Java代码如下:
import java.util.Scanner;
public class Main {
static int n, ans, k, coe, len, outcome;
static int[] c = new int[10011];
static char[] e = new char[10011];
static char[] s = new char[10011];
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
e = sc.next().toCharArray();
ans = calculate();
System.out.println(ans);
sc.close();
}
static void sort(int x) {
int i, j, t;
for (i = 1; i < x; i++) {
for (j = i + 1; j > 1; j--) {
if (c[j] < c[j - 1]) {
t = c[j - 1];
c[j - 1] = c[j];
c[j] = t;
} else {
break;
}
}
}
}
static int calculate() {
int i, j;
k = outcome = 0;
len = e.length;
if (e[0] != '-') {
for (i = len + 1; i > 0; i--) {
s[i] = s[i - 1];
}
s[0] = '+';
len++;
} else {
s = e.clone();
}
for (i = 0; i < len; i += 3) {
if (s[i] == '+') {
coe = 1;
} else {
coe = -1;
}
i++;
j = 0;
while ('0' <= s[i] && s[i] <= '9') {
j *= 10;
j += s[i++] - '0';
}
if (s[i] == '*') {
i++;
} else {
j = 1;
}
coe *= j;
c[++k] = coe;
outcome += (n - (s[i] == 'a')) * coe;
}
sort(k);
for (i = 1; i <= k; i++) {
outcome += i * c[i];
}
return outcome;
}
}
阅读全文