当前位置:网站首页>每日一题——小乐乐改数字
每日一题——小乐乐改数字
2022-07-02 15:22:00 【保护小周ღ】
题目来源于牛客网
描述
小乐乐喜欢数字,尤其喜欢0和1。他现在得到了一个数,想把每位的数变成0或1。如果某一位是奇数,就把它变成1,如果是偶数,那么就把它变成0。请你回答他最后得到的数是多少。
输入描述:
输入包含一个整数n (0 ≤ n ≤ 109)
输出描述:
输出一个整数,即小乐乐修改后得到的数字。
示例1
输入:
222222
输出:
0
示例2
输入:
123
输出:
101
思路解析:
首先我们输入一个整数,然后要将整数的偶数位转换成0,奇数位变成1;那么自然而然就涉及到取数转换,接下来博主就为大家分享两种解题思路。
第一种是用数组做,优势是取数、修改数据容易,缺点是程序笨重,通用性不好,需要根据实例,做出相应的调整。
第二种是造数,通过取数,然后根据题目要求,生成一个新的数,直到输入的整数的每一项都进行了取数为止,新数制造完成。非常的好用。
造数法:
#include<stdio.h>
int main()
{
int a=0;//整数a
int k=0;//存储每一位的位数
int sum=0;//造数
scanf("%d",&a);
//定义一个i用来控制每一位的数据大小,例如:123=1*100+2*10+3*1;
//循环结束条件为整数a的每一位都取到过;
//i*=10,相当于i=i*10;因为是造数,所以要控制好每一位的大小
for(int i=1;a!=0;i*=10)
{
//与10求模即可的得出最后一位
k=a%10;
//判断该位的奇偶
if(k%2==0)
{
k=0;//如果是偶数,那么这一位为0
sum+=k;
}
else
{
k=1;//如果是奇数,那么这一位为1
sum+=k*i;//通过乘i来调整位数的大小,通过sum存储
}
//除以10,概数去掉最后一位,从而可以判断下一位
a=a/10;
}
//打印制造的数sum
printf("%d",sum);
return 0;
}
数组法:
#include<stdio.h>
int main()
{
int i = 0, j = 0;
int t[16] = { 0 };
int n;
float sum = 0;
scanf("%d",&n);
while (n)
{
//判断奇偶,以及相应的处理方式
if (n % 2 == 0||n==0)
{
t[i] = 0;
sum += t[i];
}
else
{
t[i] = 1;
sum += t[i];
}
++i;
n = n / 10;
}
//数据每一位都一样(相同)的情况
if (sum /( i +1)== t[0])
printf("%d", t[0]);
//数据开头为0,我们则输出非0以后的数据
else if (t[i] == 0)
{
for (j = i; j >=0; j--)
{
if (t[j] % 2 != 0)
while (j >=0)
{
printf("%d", t[j]);
j--;
}
}
}
//打印转换后的数据
else
while (i>=0)
{
printf("%d",t[i]);
--i;
}
return 0;
}
题目来源于牛客网:
感谢每一个观看本篇文章的朋友,更多精彩敬请期待:保护小周ღ
如有侵权请联系修改删除!
边栏推荐
猜你喜欢
Weili holdings listed on the Hong Kong Stock Exchange: with a market value of HK $500million, it contributed an IPO to Hubei
[shutter] dart data type (dynamic data type)
Connect Porsche and 3PL EDI cases
Si446 usage record (II): generate header files using wds3
Eye of depth (II) -- matrix and its basic operations
The bottom simulation implementation of vector
Sword finger offer 24 Reverse linked list
TCP拥塞控制详解 | 2. 背景
Timing / counter of 32 and 51 single chip microcomputer
Map集合详细讲解
随机推荐
一年頂十年
About me
智能垃圾桶(五)——点亮OLED
si446使用记录(一):基本资料获取
Navigateur Chrome pour un accès rapide au stackoverflow
Timing / counter of 32 and 51 single chip microcomputer
IDEA2021.1 安装教程
How to quickly distinguish controlled components from uncontrolled components?
TCP congestion control details | 2 background
PCL知识点——体素化网格方法对点云进行下采样
2022 interview questions
vector的底层模拟实现
Listing of chaozhuo Aviation Technology Co., Ltd.: raising 900million yuan, with a market value of more than 6billion yuan, becoming the first science and technology innovation board enterprise in Xia
A few lines of code to complete RPC service registration and discovery
Meanings of SNAT, DNAT and masquerade in iptables
What is agile development process
Geoserver: publishing PostGIS data sources
Nexus Introduction and Xiaobai use idea Packaging and Upload to Nexus 3 private service detailed tutoriel
The bottom simulation implementation of vector
Does digicert SSL certificate support Chinese domain name application?