zoukankan      html  css  js  c++  java
  • [LeetCode]Divide Two Integer

    Divide two integers without using multiplication, division and mod operator.

    思考:位运算。AC的时候真的想说一句“尼玛。。“,用unsigned int 超时,莫名其妙,折腾到半夜,百度一下改为long long过了。。我也不明白到底怎么回事,毕竟不是CS出身,哎。。太晚了,明天再看。

    VC不支持long long,珍爱生命,远离VC。

    class Solution {
    public:
        int divide(int dividend, int divisor) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            assert(divisor!=0);
    		if(dividend==0) return 0;
    		bool flag=true;
    		if((dividend>0&&divisor<0)||(dividend<0&&divisor>0)) flag=false;
    		long long c=dividend;
    		long long d=divisor;
    		long long a=abs(c);
    		long long b=abs(d);
    	    long long ret=0;
    		long long count=1;
    		while(a!=0)
    		{
    			b=abs(d);
    			if(a<b) 
    			{
    				a=0;
    				count=0;
    				break;
    			}
    			count=1;
    			while(b<a)
    			{
    				b<<=1;
    				count<<=1;
    			}	
    			if(b!=a)
    			{
    				b>>=1;
    				count>>=1;
    			}
    			a-=b;
    			ret+=count;
    		}
    		return (flag)?ret:-ret;
        }
    };
    

      

  • 相关阅读:
    格式与布局
    iframe
    tp
    头信息
    php 文件下载
    socket
    Flex 布局2
    Flex 布局
    下拉刷新
    选取一种类中含有某一属性值得元素的集合
  • 原文地址:https://www.cnblogs.com/Rosanna/p/3440800.html
Copyright © 2011-2022 走看看