通过移位的方式实现相加算法
#include <iostream>
?
//加減乘除,都是靠位運算,
?
//將來從事手機端,嵌入式開發,位操作,
class jia;//聲明,只能聲明指針或者引用
?
jia? *pjia1;
jia *& pjia2 = pjia1;
//jia& jia2;
//jiajia1;
?
//intx=1024
?
class jia
{
public:
??? jia(int a, int b) :x(a), y(b)
??? {
??? }
??? int jiafa()
??? {
??????? return x + y;
??? }
??? int getx()
??? {
??????? return x;
??? }
??? int gety()
??? {
??????? return y;
??? }
??? int newjiafa(int a, int b)
??? {
??????? if (a == 0)
??????? {
??????????? return b;
??????? }
??????? else if (b == 0)
??????? {
??????????? return a;
??????? }
??????? else
??????? {
??????????? int res = a^b;//先求結果
??????????? int wei = (a&b) << 1;//進位,左移,乘以2,
??????????? //a+b=a^b+(a&b)<<1;
??????????? std::cout << "res=" << res << " " << "wei=" << wei << "\n";
??????????? return newjiafa(res, wei);
??????? }
??? }
?
private:
??? int x;
??? int y;
};
?
int newjiafa(int a, int b)
{
??? if (a == 0)
??? {
??????? return b;
??? }
??? else if (b == 0)
??? {
??????? return a;//讓相與慢慢趨勢于0
??? }
??? else
??? {
??????? int res = a^b;//先求結果
??????? int wei = (a&b) << 1;//進位,左移,乘以2,
??????? //a+b=a^b+(a&b)<<1;//表達式
?
??????? std::cout << "res=" << res << " " << "wei=" << wei << "\n";
??????? return newjiafa(res, wei);
??? }
}
?
void main1()
{
??? //std::cout << newjiafa(11, 22) << std::endl;
?
??? jia? jia1(10, 9);
??? std::cout << jia1.jiafa() << std::endl;
??? std::cout << jia1.newjiafa(jia1.getx(), jia1.gety()) << std::endl;
??? std::cin.get();
}
?
void main2()
{
??? int num;
??? std::cin >> num;
??? int i = 0;
??? while (num)
??? {
??????? i++;
??????? num &= num - 1;//讓數據趨向于0
??? }
?
??? std::cout << i << std::endl;
??? std::cin.get();
??? std::cin.get();
}
?
int get1(int num)
{
??? int count = 0;//表示位數
??? unsigned int? flag = 1;//0000001? flag
??? //?? 1111? num
?
??? //0000001????? 1
??? //flag? 000001
??? //num????? 1111
?
??? //flag?? 0000010
??? //num????? 1111
?
??? //? 0000010
??? //flag?? 0000100
??? //num????? 1111
?
??? //? 00000100
??? //flag?? 0001000
??? //num?????? 1111
?
??? //? 000001000
??? //flag?? 00010000
??? //num?????? 1111
??? //0
??? while (flag)
??? {
??????? std::cout << num << "? " << flag << std::endl;
??????? if (num & flag) //不為0就自增
??????? {
??????????? count++;
??????? }
??????? flag = flag << 1;
??? }
?
??? return count;
}
?
void main()
{
??? int num;
??? std::cin >> num;
??? int i = 0;
?
??? i = get1(num);
??? std::cout << i << std::endl;
??? std::cin.get();
??? std::cin.get();
}
總結
以上是生活随笔為你收集整理的通过移位的方式实现相加算法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: override,final的使用,两者
- 下一篇: istringstream字符串流,实现