基础练习
十六进制转八进制1:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
long long pow(long long x, long long y) {
long long ans = 1;
while (y > 0) {
if (y & 1) {
ans *= x;
}
x *= x;
y >>= 1;
}
return ans;
}
int main() {
int t;
cin >> t;
string s1, s2;
long long n;
while (t--) {
cin >> s1;
s2 = "";
n = 0;
for (int i = 0; i < s1.size(); i++) {
if (s1[i] <= '9' && s1[i] >= '0') {
n += (s1[i] - '0') * pow(16, s1.size() - i - 1);
} else {
n += (s1[i] - 'A' + 10) * pow(16, s1.size() - i - 1);
}
}
int a, b;
while (n) {
a = n % 8;
s2 += (a + '0');
n /= 8;
}
for (int i = s2.size() - 1; i >= 0; i--) {
cout << s2[i];
}
cout << endl;
}
return 0;
}
十六进制转八进制2:
#include<iostream>
using namespace std;
//思路:100000位的十六进制数,这么大的数不好直接处理,以二进制字符串转换为八进制即可
int main(){
int n;
cin>>n;
while(n--){
string s;
cin>>s;
int len1 = s.length();
string res1="";
//将16进制转换为二进制字符串
for (int i=0;i<len1;i++){
switch(s[i]){
case '0': res1 += "0000"; break;
case '1': res1 += "0001"; break;
case '2': res1 += "0010"; break;
case '3': res1 += "0011"; break;
case '4': res1 += "0100"; break;
case '5': res1 += "0101"; break;
case '6': res1 += "0110"; break;
case '7': res1 += "0111"; break;
case '8': res1 += "1000"; break;
case '9': res1 += "1001"; break;
case 'A': res1 += "1010"; break;
case 'B': res1 += "1011"; break;
case 'C': res1 += "1100"; break;
case 'D': res1 += "1101"; break;
case 'E': res1 += "1110"; break;
case 'F': res1 += "1111"; break;
}
}
//二进制字符串每四个数就是一个16进制数,每3个数就是一个8进制数,这里可能存在缺0的情况,需要补充
int len2=res1.length() ;
switch(len2%3){
case 1: res1 = "00"+res1; break;
case 2: res1 = "0"+res1; break;
}
//此时的res1就是一个合法的二进制表示8进制的字符串了,下面开始生成八进制字符串了
string res2="";
len2=res1.length();
for (int i=0;i<len2;i+=3){
string t = res1.substr(i,3);
// 避免因为000带来导致转为为八进制时候有前导0
if (i==0&&t=="000") res2+="";
else res2 += (4*((t[0])-'0')+ 2*((t[1])-'0' )+ ((t[2])-'0'))+'0';
}
cout<<res2<<endl;
}
return 0;
}
特殊回文数:枚举暴力+小优化
#include <iostream>
using namespace std;
//枚举暴力+小优化
int main() {
int n;
cin >> n;
//枚举五位数
for (int i = 1; i <= 9; i++) {
for (int j = 0; j <= 9; j++) {
for (int k = 0; k <= 9; k++) {
if (i * 2 + j * 2 + k == n) {
cout << i * 10000 + j * 1000 + k * 100 + j * 10 + i << endl;
}
}
}
}
//枚举六位数
for (int i = 1; i <= 9; i++) {
for (int j = 0; j <= 9; j++) {
for (int k = 0; k <= 9; k++) {
if (i * 2 + j * 2 + k * 2 == n) {
cout << i * 100000 + j * 10000 + k * 1000 + k * 100 + j * 10 + i << endl;
}
}
}
}
return 0;
}
算法训练:
1、动态规划
告别动态规划,连刷40道动规算法题,我总结了动规的套路 - 云+社区 - 腾讯云 (tencent.com)
例1:印章(见收藏)?
|