zoukankan      html  css  js  c++  java
  • an easy problem(贪心)

    An Easy Problem
    Time Limit: 1000MS   Memory Limit: 65536K
    Total Submissions: 8333   Accepted: 4986

    Description

    As we known, data stored in the computers is in binary form. The problem we discuss now is about the positive integers and its binary form. 

    Given a positive integer I, you task is to find out an integer J, which is the minimum integer greater than I, and the number of '1's in whose binary form is the same as that in the binary form of I. 

    For example, if "78" is given, we can write out its binary form, "1001110". This binary form has 4 '1's. The minimum integer, which is greater than "1001110" and also contains 4 '1's, is "1010011", i.e. "83", so you should output "83".

    Input

    One integer per line, which is I (1 <= I <= 1000000). 

    A line containing a number "0" terminates input, and this line need not be processed.

    Output

    One integer per line, which is J.

    Sample Input

    1
    2
    3
    4
    78
    0
    

    Sample Output

    2
    4
    5
    8
    83
    

    Source

    【思路】:会发现 78 :1001110  
                            83:1010011
      83的二进制是78二进制从右往做扫扫到01,将这个1左移一位,剩下的1右移
    网上有种方法一行代码的大神 渣渣我直接看不懂 
    这是哪门子贪心?orz  bb我要狗带了
    【代码】
     1 //    Presentation Error(展示错误orz)    mlgb没换行符报错 第一次出现这种错误整个人都蒙圈了 
     2 #include<iostream>
     3 #include<cstdio>
     4 #include<cstdlib>
     5 #include<cstring>
     6 using namespace std;
     7 int er[100001];
     8 int main()
     9 {
    10     int n;
    11     while(cin>>n&& n)//当能输出且不为零时 
    12     {
    13         int k=0,tot=0;
    14         memset(er,0,sizeof(er));
    15         while(n)//计算二进制 
    16         {
    17             er[++k]=n%2;
    18             n/=2;
    19         }
    20         k++;
    21         for(int i=1;i<=k;i++)
    22         {
    23             if(er[i]==1)//找1的个数 
    24             {
    25                 tot++;
    26                 er[i]=0;
    27             if(er[i+1]==0)//从低位到高位找01 
    28             {
    29                 er[i+1]=1;//找到了就改为1; 相当于左移了 
    30                 break;
    31                 }    
    32             }
    33         }
    34         for(int i=1;i<=tot-1;i++)
    35         {
    36             er[i]=1;//将tot-1个1放在末尾,(右移),tot-1是因为其中一个左移了 
    37         }
    38         int sum=0;
    39         for(int i=k;i>=1;i--)//将二进制转换为十进制输出 
    40         {
    41             sum=sum*2+er[i];
    42         }
    43         printf("%d
    ",sum);
    44     }
    45     return 0;
    46 }
  • 相关阅读:
    占满屏幕的宽高,当把textarea换成其他标签的时候,怎么才能编辑?
    鼠标点击文本框后,里面的文字就消失或全选中
    jquery中选取兄弟节点的方法
    文本出现省略号
    滚动条的样式
    省略号的样式。
    input的placeholder在ie9下不兼容的结局办法。
    [CF1097D] Makoto and a Blackboard
    [CF552C] Vanya and Scales
    [CF1353E] K-periodic Garland
  • 原文地址:https://www.cnblogs.com/zzyh/p/6641822.html
Copyright © 2011-2022 走看看