2017校招真题编程训练--幸运数 进制转换

时间限制:1秒  空间限制:32768K  热度指数:13443
 算法知识视频讲解

题目描述

小明同学学习了不同的进制之后,拿起了一些数字做起了游戏。小明同学知道,在日常生活中我们最常用的是十进制数,而在计算机中,二进制数也很常用。现在对于一个数字x,小明同学定义出了两个函数f(x)和g(x)。 f(x)表示把x这个数用十进制写出后各个数位上的数字之和。如f(123)=1+2+3=6。 g(x)表示把x这个数用二进制写出后各个数位上的数字之和。如123的二进制表示为1111011,那么,g(123)=1+1+1+1+0+1+1=6。 小明同学发现对于一些正整数x满足f(x)=g(x),他把这种数称为幸运数,现在他想知道,小于等于n的幸运数有多少个?

输入描述:

每组数据输入一个数n(n<=100000)

输出描述:

每组数据输出一行,小于等于n的幸运数个数。
示例1

输入

21

输出

3

#include <cstdio>
#include <cstring>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <string>
#include <cstdlib>
#include <stack>
#include <map>
#include <set>
#include <queue>
using namespace std;
typedef long long ll;
const int maxn = 100000+10;
int sum[maxn];
int check1(int n)
{
    int cnt=0;
    while(n)
    {
        cnt+=n%10;
        n/=10;
    }
    return cnt;
}
int check2(int n)
{
    int cnt=0;
    while(n)
    {
        cnt+=n%2;
        n/=2;
    }
    return cnt;
}
void work()
{
    sum[0]=0;
    for(int i=1;i<=100000;i++)
    {
        sum[i]=sum[i-1];
        if(check1(i)==check2(i))
            sum[i]++;
    }
}
int main(void)
{
    int n;
    work();
    while(scanf("%d",&n)!=EOF)
        printf("%d\n",sum[n]);
    return 0;
}
时间限制:1秒  空间限制:32768K  热度指数:13051
 算法知识视频讲解

题目描述

给定一个十进制数M,以及需要转换的进制数N。将十进制数M转化为N进制数

输入描述:

输入为一行,M(32位整数)、N(2 ≤ N ≤ 16),以空格隔开。

输出描述:

为每个测试实例输出转换后的数,每个输出占一行。如果N大于9,则对应的数字规则参考16进制(比如,10用A表示,等等)
示例1

输入

7 2

输出

111
#include <cstdio>
#include <cstring>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <string>
#include <cstdlib>
#include <stack>
#include <map>
#include <set>
#include <queue>
using namespace std;
typedef long long ll;
char s[1000];
void work(int n,int m)
{
    int cnt=0;
    while(n)
    {
        int temp = n%m;
        if(temp>9)
            s[cnt++]=temp-10+'A';
        else
            s[cnt++]=temp+'0';
        n/=m;
    }
    for(int i=cnt-1;i>=0;i--)
        printf("%c",s[i]);
    puts("");
}
int main(void)
{
    int n,m;
    while(cin>>n>>m)
    {
        if(n<0)
            printf("-"),n*=-1;
        work(n,m);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值