We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
importjava.io.File;importjava.io.IOException;importjava.util.Scanner;/** * @author Oleg Cherednik * @since 17.06.2020 */publicclassSolution{publicstaticvoidmain(String[]args)throwsIOException{try(Scannerscan=newScanner(newFile("e:/input01.txt"))){intab_size=scan.nextInt();intqueries_size=scan.nextInt();scan.nextLine();intsize=(ab_size+Result.BITS_PER_INDEX)/Result.BITS_PER_INDEX;long[]a=strToNum(newlong[size],scan.nextLine());long[]b=strToNum(newlong[size],scan.nextLine());Result.changeBits(a,b,queries_size,scan);}}privatestaticlong[]strToNum(long[]arr,Stringstr){inti=0;intj=str.length();for(;j>=Result.BITS_PER_INDEX;j-=Result.BITS_PER_INDEX)arr[i++]=Long.parseLong(str.substring(j-Result.BITS_PER_INDEX,j),2);if(j>0)arr[i]=Long.parseLong(str.substring(0,j),2);returnarr;}}classResult{/* * Complete the 'changeBits' function below. * * The function accepts following parameters: * 1. STRING a * 2. STRING b * 3. STRING_ARRAY queries */publicstaticfinalbyteBITS_PER_INDEX=63;publicstaticvoidchangeBits(long[]a,long[]b,intqueries_size,Scannerscan)throwsIOException{long[]sum=newlong[a.length];booleandirty=true;StringBufferbuf=newStringBuffer(queries_size);while(queries_size>0){Stringcommand=scan.next();intidx=scan.nextInt();if("get_c".equals(command)){if(dirty){add(a,b,sum);dirty=false;}buf.append(get(sum,idx));}else{bytex=scan.nextByte();set("set_a".equals(command)?a:b,idx,x);dirty=true;}queries_size--;}System.out.print(buf);}privatestaticvoidadd(long[]one,long[]two,long[]sum){byteremainder=0;for(inti=0;i<sum.length;i++){sum[i]=one[i]+two[i]+remainder;remainder=(byte)((sum[i]>>BITS_PER_INDEX)&1L);}}privatestaticbyteget(long[]ar,intbit){inti=bit/BITS_PER_INDEX;bit%=BITS_PER_INDEX;return(byte)((ar[i]>>bit)&1L);}privatestaticvoidset(long[]arr,intbit,byteval){inti=bit/BITS_PER_INDEX;bit%=BITS_PER_INDEX;arr[i]=(val==0)?arr[i]&~(1L<<bit):arr[i]|(1L<<bit);}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Changing Bits
You are viewing a single comment's thread. Return to all comments →
This is Java solution: