三道编程题,2小时,不难。
拿别人的题做的,应该能AC,没有提交
第一题 求26进制的和
给出两个26进制的数,求和
思路:
求和,依次加起来,求模,另外找一个数组计算进位就好。
Java AC代码
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a = sc.next();
String b = sc.next();
int[] as = charToint(a.toCharArray());
int[] bs = charToint(b.toCharArray());
if (as.length >= bs.length) {
add(as, bs);
} else {
add(bs, as);
}
}
private static void add(int[] a, int[] b) {
int jw = 0;
for (int i = 0; i < b.length; i++) {
int tmp = a[a.length - i - 1] + b[b.length - i - 1] + jw;
a[a.length - i - 1] = tmp % 26;
jw = tmp / 26;
}
for (int i = b.length; i < a.length; i++) {
if (jw == 0) {
break;
}
int tmp = a[a.length - i - 1] + jw;
a[a.length - i - 1] = tmp % 26;
jw = tmp / 26;
}
if (jw != 0) {
System.out.print((char) (jw + 'a'));
syso(a);
}else {
syso(a);
}
}
private static void syso(int[] a) {
for (int i = 0; i < a.length; i++) {
System.out.print((char) (a[i] + 'a'));
}
}
private static int[] charToint(char[] arr1) {
int[] result = new int[arr1.length];
for (int i = 0; i < result.length; i++) {
result[i] = arr1[i] - 'a';
}
return result;
}
}
第二题:
思路:
1. 遍历第一个字符串,vector记录字符是否存在
2. 遍历第二个字符串,判断字符在vector中对应值是否为1
3. vector中对应值是否为0,false 否则输出true
代码:
#include <vector>
#include <string>
#include <iostream>
using namespace std;
int arr[26];
int main()
{
string str1, str2;
cin >> str1 >> str2;
int arr[26];
bool flag = true;
for(int i=0; i<str1.size(); i++){
int temp1 = str1[i]-'A';
arr[temp1] = 1;
}
for(int i=0; i<str2.size(); i++){
int temp2 = str2[i]-'A';
if(arr[temp2] != 1){
flag = false;
break;
}
}
cout << flag << endl;
return 0;
}
第三题:
这道题似乎样例给错了,
如果样例给的是对的,当数量相等时按照ASCII和判断大小
如果样例给的是错的,当数量相等时直接按照a.val< b.val判断大小
假设样例是对的,给定以下代码
思路:
1. struct中key代表字符串数量,val代表字符串,sum代表字符串ASCII码值的和
2. 遍历第一个字符串,截取字符串,并记录字符串对应数量,组成node存入vector中
3. 定义cmp比较函数,对vector数组进行排序
4. 遍历输出
代码:
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
struct node{
int key;
string val;
int sum;
};
bool cmp(node a, node b){
if(a.key != b.key)
return a.key < b.key;
if(a.key==b.key && a.sum!=b.sum)
return a.sum < b.sum;
}
int main()
{
string str;
cin >> str;
vector<node> arr;
string s = "";
int xint = 0;
int xsum = 0;
for(int i=0; i<str.size(); i++){
node temp;
if((str[i]>='a'&&str[i]<='z')||(str[i]>='A'&&str[i]<='Z')){
s += str[i];
if(str[i]>='a' && str[i]<='z')
xsum += (str[i]-'a');
else
xsum += (str[i]-'A');
}
if(str[i]>='0' && str[i]<='9')
xint = xint*10 + (str[i]-'0');
if( (str[i]>='0'&&str[i]<='9') &&
(i==str.size()-1 || (str[i+1]<'0'||str[i+1]>'9'))
){
temp.key = xint;
temp.val = s;
temp.sum = xsum;
arr.push_back(temp);
xint = 0;
s = "";
xsum = 0;
}
}
sort(arr.begin(), arr.end(), cmp);
string res = "";
for(int i=0; i<arr.size(); i++){
for(int j=0; j<arr[i].key; j++)
res += arr[i].val;
}
cout << res << endl;
return 0;
}