15
作者:
LC_toccc
,
2024-10-22 22:58:48
,
所有人可见
,
阅读 1
矩阵的对角元素之和
//矩阵对角线元素之和
//算法思想:遍历二维数组,当行列号相加为4时,即为对角线元素,加和;
#include<iostream>
using namespace std;
const int N = 1000;
int main(){
int n,res;
int g[N][N];
cin >> n;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= n; j++){
cin >> g[i][j];
if(i+j == 4) res += g[i][j];
if(i == j) res += g[i][j];
}
}
cout << res << endl;
return 0;
}
统计字符个数
//算法思想:遍历字符串,利用ASCII码大小关系区分字符,n,c,t分别存储数字,字母,其他字符数量;
#include<iostream>
using namespace std;
int main(){
string s;
getline(cin, s);
int i = 0,n = 0,c = 0,t = 0;
while(i < s.size()){
if(s[i] >= '0' && s[i] <= '9') n++;
else if((s[i] >= 'a' && s[i] <= 'z') || (s[i] >= 'A' && s[i] <= 'Z')) c++;
else t++;
i++;
}
cout << n << " " << c << " " << t << " ";
return 0;
}
统计单链表中的节点的值等于给定值x的节点数。
//算法思想:遍历单链表,若结点值与给定值相等则结果加一;
#include<iostream>
using namespace std;
struct ListNode{
int val;
ListNode *next;
ListNode(int x): val(x), next(NULL){}
};
ListNode *head = new ListNode(-1);
void headAdd(int t){
if(head -> val == -1) head -> val = t;
else{
ListNode *node = new ListNode(t);
node -> next = head;
head = node;
}
}
int main(){
int n,x,res = 0;
cin >> n >> x;
while(n--){
int t;
cin >> t;
headAdd(t);
}
for(ListNode *p = head -> next; p; p = p -> next){
if(p -> val == x) res ++;
}
cout << res;
return 0;
}