当前位置:网站首页>【Day_04 0421】进制转换
【Day_04 0421】进制转换
2022-07-26 06:08:00 【安河桥畔】
进制转换
题目来源
牛客网:进制转换
题目描述
给定一个十进制数M,以及需要转换的进制数N。将十进制数M转化为N进制数
输入描述
输入为一行,M(32位整数)、N(2 ≤ N ≤ 16),以空格隔开。
输出描述
为每个测试实例输出转换后的数,每个输出占一行。如果N大于9,则对应的数字规则参考16进制(比如,10用A表示,等等)
示例1
输入
7 2
输出
111
思路分析
- 进制转换的基本思路是取模,然后除以要转换的进制,直到除的结果为0
- 对负数进行标记,0直接打印结果
- 除的结果有大于10的数,要用ABCD等字母表示,所以采用使用string保存最终的结果
- 定义一个字符串存放0-F,16个数字,计算的结果映射到数组中得到对应的值
- 没得到一个结果拼接到字符串中,最后将字符串逆置,并打印结果
代码展示
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main()
{
int m = 0;
int n = 0;
string num = "0123456789ABCDEF";//结果集映射表
while (cin >> m >> n)
{
string str = "";
//m为0
if (m == 0)
{
cout << '0';
continue;
}
int flag = 0;//标记正负
if (m < 0)
{
flag = 1;
m = -m;
}
while (m)
{
//进制转换的方法,取模,除以要转换的进制数,直到结果为0
int temp = m % n;
str += num[temp];
m /= n;
}
if (flag)
{
str += '-';
}
//逆置字符串
reverse(str.begin(), str.end());
cout << str << endl;
}
return 0;
}
边栏推荐
猜你喜欢

VRRP principle and basic commands

VRRP protocol and experimental configuration

Interview difficulties: difficulties in implementing distributed session, this is enough!

The time complexity of two recursive entries in a recursive function

某公司给每个工位装监控:只为看员工写代码?

Niuke network: TOPK problem of additive sum between two ordinal groups

递归处理——子问题

Flex layout

金仓数据库 KingbaseES SQL 语言参考手册 (7. 条件表达式)

软件测试面试题全网独家没有之一的资深测试工程师面试题集锦
随机推荐
Convolutional neural network (II) - deep convolutional network: case study
Knowledge precipitation I: what does an architect do? What problems have been solved
YOLOv7: Trainable bag-of-freebies sets new state-of-the-art for real-time object detectors
Unity2d animator cannot create transition
YOLOv6:又快又准的目标检测框架开源啦
Registration conditions for system integration project management engineer (intermediate level of soft exam) in the second half of 2022
卸载手机自带APP的操作步骤
Sequential action localization | fine grained temporal contrast learning for weak supervised temporal action localization (CVPR 2022)
Calling mode and execution sequence of JS
递归处理——子问题
Leetcode:741. picking cherries
Kingbasees SQL language reference manual of Jincang database (7. Conditional expression)
PHP 多任务秒级定时器的实现方法
Latex同时合并表格的多行多列
Xiao He shows his sharp corners and says hello to flutter app
Mysql45 talking about infrastructure: how is an SQL query executed?
Kingbasees SQL language reference manual of Jincang database (11. SQL statement: abort to alter index)
Code Runner for VS Code,下载量突破 4000 万!支持超过50种语言
Taobao pinduoduo Tiktok 1688 Suning taote jd.com and other keyword search commodity API interfaces (keyword search commodity API interface, keyword search commodity list interface, classification ID s
1.12 basis of Web Development