一些笔试题(C/C++)

1.there are two variables, don't use if.. else or ?: or switch or other judgement statements,find out the biggest number of the two numbers.

   返回2个数中较大的数,不使用if else "?:" 或switch 语句

    

复制代码
 1 // return the biggest number without any judgement statements.
 2 // create by Young 
 3 // date 20130707
 4  #include <iostream>
 5  #include<math.h>
 6  using namespace std; 
 7  int max(int first_number, int second_number)
 8  {
 9         int max_number=(abs(first_number-second_number)+first_number+second_number)/2;  //use abs avoid use if else 
10         }
11 
12  int main()
13  {
14     int result=max(13,6);
15     cout<<"the max number is:"<<result<<endl;
16      return 0;
17  }
复制代码

 

2. swap two numbers without another variable, only use the two number。

      交换2个数,只能使用这两个数,不能使用第三个变量。

int a=1,b=3;
a=a+b;
b=a-b;
a=a-b;

这样做有可能a+b比较大的时候溢出,overflow 不建议这样 可以使用:

int a=1,b=2;
a=a^b;
b=a^b;
a=a^b;

^ 按位取反

 3.字符串逆序

复制代码
 1  #include <stdio.h>
 2  #include <string.h>
 3  #include <conio.h>
 4  int main()
 5  {
 6      char  str[]="abcdefg";
 7      char temp;
 8      int len=strlen(str);
 9      for(int i=0;i<len/2;i++)
10      {
11              temp=str[i] ;
12              str[i]=str[len-1-i];
13              str[len-1-i]=temp;
14              }
15              printf("%s\n",str);
16              getch();
17      return 0;
18 
19 }
复制代码

把字符串第一位和最后一位交换,第二位和倒数第二位交换

posted @   to be crazy  阅读(427)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示