小编Man*_*hna的帖子

在一个序列中打印1到1的数字,而不实际计算1

面试问题:

制作一个输入'N'(无符号长)并打印两列的程序,第一列打印从1到N的数字(十六进制格式),第二列打印左列中数字的二进制表示中的1的数量.条件是这个程序不应该计数1s(所以没有计算'每个数''得到1s /没有除法运算符).

我试图通过利用以下事实来实现这一点:0x0到0xF中的1号可以重新用于为任何数字生成1.我粘贴代码(基本的没有错误检查.)它给出了正确的结果,但我对空间使用不满意.我该如何改进呢?(我也不确定面试官是在寻找什么).

void printRangeFasterWay(){

    uint64_t num = ~0x0 ;
    cout << " Enter upper number " ;
    cin >> num ;

    uint8_t arrayCount[] = { 0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4} ;
    // This array will store information needed to print 
    uint8_t * newCount = new uint8_t[num] ;
    uint64_t mask = 0x0 ;
    memcpy(newCount, &arrayCount[0], 0x10) ; 

    uint64_t lower = 0;
    uint64_t upper = 0xF;
    uint64_t count = 0 ;
    uint32_t zcount= 0 ; 

    do{
      upper = std::min(upper, num) ;

      for(count …
Run Code Online (Sandbox Code Playgroud)

c++ puzzle algorithm

19
推荐指数
1
解决办法
1045
查看次数

C++重载new []查询:参数的大小是多少?

我有像这样的重载运算符new []

void * human::operator new[] (unsigned long int count){
      cout << " calling new for array with size  = " << count <<  endl  ;
      void * temp = malloc(count) ;  
      return temp ; 
}
Run Code Online (Sandbox Code Playgroud)

现在打电话

human * h = new human[14] ;
Run Code Online (Sandbox Code Playgroud)

比方说sizeof(human) = 16,但计算它的打印是232,这是14*16 + sizeof(int*)= 224 + 8.

为什么要分配这个额外的空间?它在哪里记忆?因为当我打印*h或者h[0]我得到相同的结果时,所以它不在内存块的开头.它是否正确或我在这里遗漏了一些东西?

c++ overloading new-operator

8
推荐指数
1
解决办法
1812
查看次数

标签 统计

c++ ×2

algorithm ×1

new-operator ×1

overloading ×1

puzzle ×1