一些诡异的与或非计算

WARush posted @ 2010年11月01日 15:26 in 与或非的世界 with tags 逻辑运算 , 1293 阅读

1.求两个数的平均数

  1. int averagePerfect(int a, int b)  
  2. {  
  3.     return (a&b) + ((a^b) >> 1);  
  4. }  

证明如下:

设a各个位为a[31]a[30]a[29]......a[0],同理b设为b[31]b[30]b[29]......b[0]。则c=(a+b)>>1。

c[n]=(a[n]+b[n]的高位)+(a[n+1]+b[n+1]的低位)=(a[n+1]^b[n+1]>>1)+(a[n]&b[n])。

故c=(a&b)+((a^b)>>1)。

2.交换a,b两个数字

  1. int exchangePerfect(int& a, int& b)  
  2. {  
  3.     a=a^b;
  4.     b=a^b;
  5.     a=a^b;
  6.  }  

证明如下:

设a各个位为a[31]a[30]a[29]......a[0],同理b设为b[31]b[30]b[29]......b[0]。

a=a^b:a[n]=a[n]^b[n]

b=a^b:b[n]=a[n]^b[n] ^b[n]=a[n]

a=a^b:a[n]=a[n]^b[n] ^a[n]^b[n] ^b[n]=a[n]^b[n]^a[n]=b[n]^a[n]^a[n]=b[n]

如此便完成了交换。

我们尝试证明更加一般的东西

a+b=

设a各个位为a[31]a[30]a[29]......a[0],同理b设为b[31]b[30]b[29]......b[0]。

  • 无匹配
  • 无匹配
AP 6th Class Telugu 说:
2022年9月29日 20:22 Telugu is the first or mother language for all Telugu Medium students studying at the state board of Andhra Pradesh. Those Class 6th Standard students studying other medium schools have chosen Telugu as a Second or Third language from their electives. AP 6th Class Telugu Question Paper Every government and private school on the state board is working with SCERT Syllabus & curriculum. Telugu is the first or mother language for all Telugu Medium students studying at the state board of Andhra Pradesh. Those Class 6th Standard students studying other medium schools have chosen Telugu as a Second or Third language from their electives.
apple.com/bill 说:
2023年7月20日 23:24

Manchmal sind wir schockiert oder besorgt über einige unerwartete Apple-Rechnungsbelastungen, die in Form von Textnachrichten oder E-Mails durchscheinen. Diese Arten von ungewohnten Zahlungen werden häufig auf apple.com/bill für ihre Apple-ID-Kunden angezeigt, die sich nach monatlichen und jährlichen Kontoauszugstransaktionen erkundigen. Dies liegt daran, dass ihre Apple-IDs gehackt wurden oder Kreditkarteninformationen entwendet wurden und ein unschuldiges Kind oder Familienmitglied ohne ihr Wissen eingekauft hat.

JAC Board 6th Quest 说:
2023年9月14日 15:19

State Council of Educational Research and Training (SCERT) Jharkhand has Going to Conducted High School Aunval Exam 2024, SCERT Jharkhand which is Mainly Responsible for Conducting Exam Every year, This SCERT Jharkhand 6th Exam Very Year More Than 25 Laks of Students Attended, SCERT Jharkhand is Administered by the State Government of Jharkhand and Thrives to Improve the Quality of JAC Board 6th Question Paper 2024 Education in the state.SCERT Jharkhand is also Responsible for Prescribing the SCERT Jharkhand Model Paper 2024 for the Students Studying in the Jharkhand Affiliated Schools, Jharkhand Question Paper 2024 Designed by Senior Experts Study Materiel help the Students to get an idea about the Final Exam 2024.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter