Sicily 1721. Gray code

格雷码的第n位等于对应的二进制码的第n-1位和第n位的异或,而最左边的第1位是相同的。这道题最好用printf以%s进行输出,可以节约不少时间。而至于题目是Special Judge,以其他形式进行排列是否可以得到更好的结果就不得而知了。

Run Time: 0.04sec

Run Memory: 288KB

Code Length: 731Bytes

Submit Time: 2013-02-28 22:06:32

// Problem#: 1721
// Submission#: 1928852
// The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
// URI: http://creativecommons.org/licenses/by-nc-sa/3.0/
// All Copyright reserved by Informatic Lab of Sun Yat-sen University
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;

int main()
{
    int n;
    char code[ 16 ], gray[ 17 ];
    int i, j;

    while ( scanf( "%d", &n ) && n ) {
        memset( code, '0', sizeof( code ) );
        gray[ n ] = '\0';
        for ( i =  powl( 2, n ); i > 0; i-- ) {
            gray[ 0 ] = code[ 0 ];
            for ( j = 1; j < n; j++ )
                gray[ j ] = ( code[ j - 1 ] == code[ j ] ? '0': '1' );
            printf( "%s\n", gray );

            for ( j = n - 1; j >= 0; j-- ) {
                code[ j ] = ( code[ j ] == '1' ? '0': '1' );
                if ( code[ j ] == '1' )
                    break;
            }
        }
        printf( "\n" );
    }

    return 0;

}                                 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值